nginx反向代理实现获取用户真实ip
参考资料:https://www.cnblogs.com/mzhaox/p/11214747.html
用户真实ip是223.193.x.x,发送请求,请求经过Nginx A->Nginx B -> 最后到达后端服务
nginx A的关键配置:
http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; keepalive_timeout 65; client_max_body_size 10000m; server { listen 6794; root /mnt/dist; location /myapi/ { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://xxx.xxx.xxx:xxx; # nginx B的地址 }
nginx B的关键配置:
http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for" zz "$http_x_real_ip"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; # gzip include /etc/nginx/conf.ext/*.conf; client_max_body_size 1g; server { listen 5111; set_real_ip_from yyy.yyy.yyy.yyy; # NGINX A的IP 。如果nginx B前面有多个nginx,可以把多个nginx的IP都写上 real_ip_header X-Forwarded-For; real_ip_recursive on; root /mnt/dist; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
1.使用realip模块后,$remote_addr输出结果为真实客户端IP,可以使用$realip_remote_addr获取最后一个反向代理的IP;
2.real_ip_headerX-Forwarded-For:告知Nginx真实客户端IP从哪个请求头获取;
3.set_real_ip_from 172.25.78.0/24:告知Nginx哪些是反向代理IP,即排除后剩下的就是真实客户端IP
4.real_ip_recursive on:是否递归解析,当real_ip_recursive配置为off时,Nginx会把real_ip_header指定的请求头中的最后一个IP作为真实客户端IP;
当real_ip_recursive配置为on时,Nginx会递归解析real_ip_header指定的请求头,最后一个不匹配set_real_ip_from的IP作为真实客户端IP。