server {
listen 80;
server_name www.example.com;
location / {
proxy_pass https://1.2.3.4; # 後端服務器地址
proxy_redirect off; # 禁用後端 Location/Refresh 頭重寫
proxy_set_header Host $host; # 透傳原始 Host
proxy_set_header X-Real-IP $remote_addr; # 客戶端真實 IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 代理鏈 IP 列表
}
}
關鍵指令說明
| 指令 | 作用 |
proxy_pass | 指定上游服務器地址,支持變量、Upstream 組名 |
proxy_redirect | off 禁止 Nginx 修改後端 3xx 重定向 Location 頭;default 自動將後端域名替換為代理域名 |
proxy_set_header Host | 關鍵!後端常需原始 Host 進行虛擬主機路由、生成絕對 URL |
X-Real-IP | 單一真實客戶端 IP,方便後端日志、限流 |
X-Forwarded-For | 代理鏈路 IP 列表(客戶端, 代理1, 代理2...),$proxy_add_x_forwarded_for 自動追加 |
進階:負載均衡與健康檢查
upstream backend {
server 192.168.1.10:80 weight=3;
server 192.168.1.11:80 weight=2;
server 192.168.1.12:80 backup; # 備用節點
}
server {
location / {
proxy_pass https://backend;
proxy_next_upstream error timeout http_500 http_502 http_503 http_504; # 故障轉移
}
}