Nginx-$http_x_forwarded_for與$proxy_add_x_forwarded_for之個人見解


在裝好nginx后,默認的配置文件中日志格式如下

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

 訪問日志如下

192.168.64.131 - - [03/Feb/2022:14:54:28 +0800] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
192.168.64.1 - - [05/Jan/2022:03:56:08 -0800] "GET /favicon.ico HTTP/1.1" 404 555 "http://192.168.64.132/haha.passwd" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"

 可以看到日志顯示到用戶客戶端版本后截止,並沒有打印出$http_x_forwarded_for信息

原因分析:

個人認為$http_x_forwarded_for 設計初衷為代理透傳客戶端源IP,那么直接訪問也就不需要獲取客戶端真實IP,直接看$remote_addr即可。

 

如果改為以下配置

upstream static {
        server 192.168.64.131:80;
    }

server {
        listen       80;
        server_name  localhost;


        location ~* \.(jpg|png|gif|html)$ {
            proxy_pass http://static;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
}

日志格式

log_format access_json '{"@timestamp":"$time_local",'
    '"host":"$server_addr",'
    '"clientip":"$remote_addr",'
    '"size":$body_bytes_sent,'
    '"responsetime":$request_time,'
    '"upstreamtime":"$upstream_response_time",'
    '"upstreamhost":"$upstream_addr",'
    '"http_host":"$host",'
    '"uri":"$uri",'
    '"domain":"$host",'
    '"x_forwarded_for":"$http_x_forwarded_for",'  //接收透傳
    '"X-Real-IP":"$remote_addr",'
    '"referer":"$http_referer",'
    '"tcp_xff":"$proxy_protocol_addr",'
    '"http_user_agent":"$http_user_agent",'
    '"status":"$status"}'

測試訪問

http://192.168.64.130/index.html
查看后端192.168.64.131的訪問日志,可以看到已經透傳了客戶端真實IP192.168.64.1給后端。
{"@timestamp":"03/Feb/2022:15:35:12 +0800",    '"host":"192.168.64.131",'    '"clientip":"192.168.64.130",'    '"size":0,'    '"responsetime":0.000,'    '"upstreamtime":"-",'    '"upstreamhost":"-",'    '"http_host":"192.168.64.130",'    '"uri":"/index.html",'    '"domain":"192.168.64.130",'    '"x_forwarded_for":"192.168.64.1",'"X-Real-IP":"192.168.64.130",    '"referer":"-",'    '"tcp_xff":"",'    '"http_user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36",'    '"status":"304"}'

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM