如何将请求IP从NGINX转发到node.js应用程序? [英] How to forward request IP from NGINX to node.js application?

查看:255
本文介绍了如何将请求IP从NGINX转发到node.js应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have NGINX running as reverse proxy which forwards all http and https traffic to my node.js application, which listens to localhost:port

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

However the issue I have is that the node.js application sees all incoming requests as coming from ::ffff:127.0.0.1

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

How can I change the NGINX config such that the real IP will be passed through and forwarded to the node.js application?

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";
}


}

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

The express.js/node.js application processes req.ip and has app.enable('trust proxy'); at startup

推荐答案

Express.js官方网站上有

Express.js official site has this guide. Instructions:

    js中的
  1. app.set('trust proxy', true).
  2. nginx.conf中的
  3. proxy_set_header X-Forwarded-For $remote_addr
  4. 您现在可以从req.ip属性中读取客户端IP地址
  1. app.set('trust proxy', true) in js.
  2. proxy_set_header X-Forwarded-For $remote_addr in nginx.conf
  3. You can now read-off the client IP address from req.ip property

这篇关于如何将请求IP从NGINX转发到node.js应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆