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"}'
越学越感到自己的无知