gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:49:13 24 4
gpt4 key购买 nike

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


}

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

最佳答案

Express.js 官方网站有这个 guide 。使用说明:

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

关于node.js - 如何将请求IP从NGINX转发到node.js应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55570505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com