如何将请求 IP 从 NGINX 转发到 node.js 应用程序?

cod*_*456 11 ubuntu nginx node.js express

我有 NGINX 作为反向代理运行,它将所有 http 和 https 流量转发到我的 node.js 应用程序,它侦听 localhost:port

但是,我遇到的问题是 node.js 应用程序将所有传入请求视为来自 ::ffff:127.0.0.1

如何更改 NGINX 配置,以便将真实 IP 传递并转发到 node.js 应用程序?

server {
    listen 80;
    listen [::]:80;
    listen 443;
    listen [::]:443;

    root /var/www/example.com/html;
    index index.html index.htm;

    server_name example.com;

location / {
proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://localhost:myport;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

 # Requests for socket.io are passed on to Node on port x
  location ~* \.io {
  proxy_set_header X-Real-IP   $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header Host $http_host;
  proxy_set_header X-NginX-Proxy true;

  proxy_pass http://localhost:myport;
  proxy_redirect off;

  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
}


}
Run Code Online (Sandbox Code Playgroud)

编辑: express.js/node.js 应用程序处理 req.ip 并具有 app.enable('trust proxy'); 启动时

hac*_*ape 20

Express.js 官方网站有这个指南。指示:

  1. app.set('trust proxy', true) 在js中。
  2. proxy_set_header X-Forwarded-For $remote_addr 在 nginx.conf 中
  3. 您现在可以从req.ip属性中读取客户端 IP 地址