在nginx配置文件中添加以下内容:

set_real_ip_from 0.0.0.0/0; # 允许所有IP访问
real_ip_header X-Forwarded-For; # 从HTTP头中获取真实IP地址

其中,set_real_ip_from指定允许哪些IP访问,可以根据实际情况进行配置;real_ip_header指定从哪个HTTP头中获取真实IP地址,一般为X-Forwarded-For

在使用了以上配置后,可以通过$remote_addr获取到反向代理服务器的IP地址,通过$http_x_forwarded_for获取到客户端的真实IP地址。例如:

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

以上配置会在访问日志中输出类似以下的内容:

192.168.1.100 - 203.0.113.1, 203.0.113.2 - [04/Jan/2022:12:34:56 +0800] "GET /index.html HTTP/1.1" 200 1234 "http://example.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36" "203.0.113.3, 203.0.113.4"

其中,$remote_addr为反向代理服务器的IP地址,$http_x_forwarded_for为客户端的真实IP地址

nginx 获取客户端真实ip地址

原文地址: https://www.cveoy.top/t/topic/cpR6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录