当使用Nginx作为反向代理时,客户端的真实IP地址会被代理服务器的IP所替代。要获取用户的真实IP地址,需要进行以下配置:
在反向代理服务器的配置文件中(通常是/etc/nginx/nginx.conf
或站点配置文件),在location
或server
块中添加以下指令:
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://backend_server;
}
在后端服务器(如Apache、Tomcat或其他Nginx实例)上,需要配置以识别这些头部信息。
set_real_ip_from 192.168.1.0/24; # 反向代理服务器的IP段
real_ip_header X-Forwarded-For;
real_ip_recursive on;
在httpd.conf
或虚拟主机配置中添加:
RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 192.168.1.0/24 # 反向代理服务器的IP段
如果你的架构中有多级反向代理,需要确保每一级都传递X-Forwarded-For头部:
proxy_set_header X-Forwarded-For "$http_x_forwarded_for, $remote_addr";
要在Nginx访问日志中记录真实IP,修改日志格式:
log_format main '$http_x_forwarded_for - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log main;
set_real_ip_from
指令限制可信代理IP范围$remote_addr
作为最后一级代理的真实IP来源配置完成后,可以通过以下方式验证:
$_SERVER['HTTP_X_FORWARDED_FOR']
查看获取的IP通过以上配置,你的反向代理架构应该能够正确获取并传递用户的真实IP地址了。