此模块需要在编译安装nginx时加上 –with-http_realip_module 参数
测试环境:
PC主机 -> nginx反向代理 -> 源nginx
192.168.6.88 -> 192.168.6.151 -> 192.168.6.114
# 192.168.6.151 中 nginx 反向代理配置 location / { proxy_pass http://192.168.6.114; proxy_set_header host t1.test.com; proxy_set_header x-forwarded-for $remote_addr,192.168.6.151,1.1.1.1; } # 192.168.6.114中nginx配置: real_ip_header x-forwarded-for; set_real_ip_from 192.168.6.151; set_real_ip_from 1.1.1.1; real_ip_recursive on; 当用PC浏览器访问反向代理nginx ip时,源nginx日志中为: 192.168.6.88 - - [07/Feb/2025:01:31:55 -0500] "GET / real_ip_header 用于配置从哪个请求头中获取真实ip。 set_real_ip_from 配置指令可以有多个,用于配置受信任的ip,移除 x-forwarded-for 字段中 set_real_ip_from 中定义的值。 real_ip_recursive 为on,先从 x-forwarded-for 中排除 set_real_ip_from 指令指定的ip,然后取最后一个ip作为客户端ip。 real_ip_recursive 为off,取x-forwarded-for中最后一个ip作为客户端ip 当 set_real_ip_from 的值都匹配不到 x-forwarded-for 中的值时,则不处理,直接用上一级代理的ip作为客户端ip(也就是 nginx反向代理机器ip )
这样可以实现在不改动后端代码的情况下获取真实客户端ip
例如php
原创文章,转载请注明。本文链接地址: https://www.rootop.org/pages/5513.html