【问题标题】:How get client real IP when using nginx server in front of node as proxy使用节点前的nginx服务器作为代理时如何获取客户端真实IP
【发布时间】:2018-05-14 07:57:53
【问题描述】:

我需要在 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();
});

【问题讨论】:

  • 您使用的是哪个代理?
  • 我在节点前面有 nginx 服务器作为代理。

标签: node.js http express proxy ip


【解决方案1】:

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

proxy_set_header X-Forwarded-For $remote_addr;

【讨论】:

  • 是的,现在req.headers['x-forwarded-for'] 标头将包含远程ip,您可以将代码简化为app.ipInfo = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  • 我的服务器配置成这样proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for
  • 这也应该可以,它会将远程 ip 附加到 X-forwarded-For 标头中的现有 ip 中,尝试在中间件中添加这一行 console.log(req.headers['x-forwarded-for']) 以查看我们是否获得远程 ip与否
  • 并使用req.ipInfo = ... 而不是app.ipInfo
  • 它返回 ip ::1
猜你喜欢
  • 1970-01-01
  • 2020-10-21
  • 2012-03-11
  • 1970-01-01
  • 2016-12-05
  • 2011-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多