首页 > 解决方案 > 由于反向代理,无法在生产中获取客户端的 IP

问题描述

我的 nodejs 后端应用程序在开发中运行良好。但现在我意识到,由于在开发中我有一个从前端到 /api 的所有请求的反向代理,所有req.ip值现在都是 localhost。

如何在不使用第三方 api 的情况下解决它?看起来我需要在客户端的 ip 到达后端之前获取它?

我正在使用 nginx 作为反向代理。

标签: javascriptnode.jsnginxipreverse-proxy

解决方案


as per Benard's suggestion, I had to add the following line to the express server file:

server.set("trust proxy", true);

then, in the nginx config:

  # node api reverse proxy
  location /api/ {
    proxy_set_header X-Forwarded-For $remote_addr; // added this
    proxy_pass http://localhost:5000/;
  }

restart the nginx and the express server, and req.ip will work.


推荐阅读