Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Nginx 反向代理核心配置:proxy_pass 與關鍵 Header 設置詳解

編輯:Linux 教學
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_redirectoff 禁止 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;  # 故障轉移
    }
}
Copyright © Windows教程網 All Rights Reserved