在节点前面使用nginx服务器作为代理时如何获得客户端真实IP

时间:2017-11-30 11:39:13

标签: node.js http express proxy ip

我需要在nodeJs中获取客户端真实IP地址,当使用nginx代理服务器时,我总是得到我的localhost(127.0.0.1)。任何人都可以帮我解决这个问题吗? 这是我的代码

app.set('trust proxy', 'loopback');
app.use(function(req, res, next) {
  app.ipInfo = req.headers['x-forwarded-for'] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress;
  next();
});

1 个答案:

答案 0 :(得分:3)

在nginx中,如果要将远程用户的IP地址传递给后端Web服务器,则必须将X-Forwarded-For标头设置为此远程IP,如下所示:

proxy_set_header X-Forwarded-For $remote_addr;