插件窝 干货文章 Nginx反向代理后无法获取客户端真实IP地址怎么解决

Nginx反向代理后无法获取客户端真实IP地址怎么解决

Forwarded Nginx 配置 真实 368    来源:    2025-04-25

Nginx反向代理后获取客户端真实IP地址的解决方案

当使用Nginx作为反向代理时,默认情况下后端服务器只能看到Nginx的IP地址,而无法获取原始客户端的真实IP。以下是几种解决方案:

方法一:配置X-Forwarded-For头

在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。

方法二:使用real_ip模块

  1. 确保Nginx编译时包含--with-http_realip_module模块
  2. 在Nginx配置中添加:
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的示例

PHP示例

$ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'];

Node.js示例

const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

Java Servlet示例

String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.isEmpty()) {
    ip = request.getRemoteAddr();
}

注意事项

  1. X-Forwarded-For头可以被伪造,重要场景应结合其他安全措施
  2. 如果使用CDN,可能需要配置CDN传递原始IP
  3. 在日志记录中,可以使用$http_x_forwarded_for变量记录真实IP

通过以上配置,您的后端服务器应该能够正确获取客户端的真实IP地址。