proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 在nginx配置中,嚴謹一點來說這配置使用在作爲代理的nginx中。
通過名字就知道,X-Forwarded-For 是一個擴展頭。HTTP/1.1(RFC 2616)協議並沒有對它的定義,它最開始是由 Squid 這個緩存代理軟件引入,用來表示 HTTP 請求端真實 IP,現在已經成爲事實上的標準,被各大 HTTP 代理、負載均衡等轉發服務廣泛使用,並被寫入 RFC 7239 (Forwarded HTTP Extension)標準之中。
用途: 可以獲取真實的代理路徑經過的各個代理的IP,記錄日誌中。
最簡單的一個模型
client ----- nginx proxy------ngxin server
在proxy代理中加入一下配置:
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
server {
listen 80;
server_name bbs.test.com;
location / {
proxy_pass http://192.168.100.10; #代理到nginx server
root html;
index index.html index.htm;
}
nginx proxy 和 nginx server的日誌格式:
log_format main '$remote_addr $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';
模擬實驗講述這個原理過程
clinet 192.168.100.20
nginx proxy 192.168.100.13
nginx server 192.168.100.10
client發起一個請求(hosts已經解析 192.168.100.20 bbs.test.com)
curl -I bbs.test.com
查看nginx proxy處的日誌: http_x_forwarded_for 字段爲: "-"
查看nginx server處的日誌: http_x_forwarded_for 字段 爲: "192.168.100.20"
client再發起一個請求:
查看nginx proxy處的日誌: http_x_forwarded_for 字段爲: "1.1.1.1"
查看nginx server處的日誌: http_x_forwarded_for 字段 爲: "1.1.1.1, 192.168.100.20"
其實這個過程就是
1 nginx proxy接收到了client的請求,發現裏面請求裏面的X-Forwarded-For字段爲1.1.1.1 所以ngixn寫入日誌的 http_x_forwarded_for的字段值爲1.1.1.1
2 由於作爲了這個請求的代理,然後ngixn設置了代理
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
的操作,將自己的X-Forwarder-For http頭部字段進行了修改,等於$proxy_add_x_forwarded_for(原有 的加上自己的IP,IP以逗號隔開) 值就爲"1.1.1.1, 192.168.100.20"
3 nginx server受到代理發過來的請求,自然記錄nginx日誌的時候讀取X-Forwarded-For字段的值的時候,值爲 "1.1.1.1, 192.168.100.20"