当使用Nginx作为反向代理时,默认情况下后端服务器只能看到Nginx的IP地址,而无法获取原始客户端的真实IP。以下是几种解决方案:
在Nginx反向代理配置中添加以下指令:
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;
}
然后在后端服务器应用中,从X-Forwarded-For
头中获取真实IP。
--with-http_realip_module
模块set_real_ip_from 代理服务器IP/网段;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
如果有多层代理,确保每一层都传递X-Forwarded-For头:
proxy_set_header X-Forwarded-For "$http_x_forwarded_for, $remote_addr";
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'];
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.isEmpty()) {
ip = request.getRemoteAddr();
}
X-Forwarded-For
头可以被伪造,重要场景应结合其他安全措施$http_x_forwarded_for
变量记录真实IP通过以上配置,您的后端服务器应该能够正确获取客户端的真实IP地址。