使用nginx和node获取ip用户

0kjbasz6  于 2023-08-03  发布在  Nginx
关注(0)|答案(3)|浏览(128)

我有一个问题与nginx和节点,因为当我想得到的ip用户与节点,在我的localhost工作正常(没有使用nginx),但在我的服务器不工作,因为它应该.我正在研究,看到节点号是第一个接收IP的,是nginx,在nginx之后向节点发送请求。则节点接收的IP是我的服务器而不是用户的IP。查看配置服务器nignx:

  1. location / {
  2. proxy_pass https://fotogena.co:8000; <-nginx send req to node
  3. proxy_http_version 1.1;
  4. proxy_set_header Upgrade $http_upgrade;
  5. proxy_set_header Connection "upgrade";
  6. proxy_set_header Host $host;
  7. proxy_connect_timeout 1000;
  8. proxy_send_timeout 1500;
  9. proxy_read_timeout 2000;
  10. }

字符串
我使用“req.connection.remoteAddress”来知道用户的IP,控制台显示我的服务器的IP。有人知道怎么解决这个问题吗?
谢谢:D
-----------2016-04-20--------
我可以解决这个问题,与这一行的nginx文件设置

  1. proxy_set_header X-Real-IP $remote_addr;


node.js

  1. req.headers['x-forwarded-for']

bpsygsoo

bpsygsoo1#

您可以配置NGINX以通过以下设置传递客户端的IP地址:

  1. location / {
  2. proxy_pass https://fotogena.co:8000;
  3. proxy_http_version 1.1;
  4. proxy_set_header Upgrade $http_upgrade;
  5. proxy_set_header Connection "upgrade";
  6. proxy_set_header Host $host;
  7. proxy_set_header X-Real-IP $remote_addr; # This line.
  8. proxy_connect_timeout 1000;
  9. proxy_send_timeout 1500;
  10. proxy_read_timeout 2000;
  11. }

字符串
然后,您可以使用来自req.headers["x-real-ip"]的HTTP标头X-Real-IP

j5fpnvbx

j5fpnvbx2#

proxy_set_header X-Real-IP $remote_addr;不适合我
在代理后运行Express应用程序时,必须将应用程序变量trust proxy设置为true。Express提供了一些其他的信任代理值,您可以在其文档中查看,但现在,我们不必介意它们。
废话不多说,下面是向您的应用显示访问者IP地址的步骤:

  1. app.set('trust proxy', true)在您的Express应用程序中。
    1.在服务器块的Nginx配置中添加proxy_set_header X-Forwarded-For $remote_addr
    1.您现在可以从req.header('x-forwarded-for')req.connection.remoteAddress读取客户端的IP地址;
    在Nginx config中
  1. location / {
  2. proxy_pass http://localhost:3001;
  3. proxy_http_version 1.1;
  4. proxy_set_header Upgrade $http_upgrade;
  5. proxy_set_header Connection 'upgrade';
  6. proxy_set_header Host $host;
  7. proxy_set_header X-Forwarded-For $remote_addr; # this line
  8. proxy_cache_bypass $http_upgrade;
  9. }

字符串

展开查看全部
6uxekuva

6uxekuva3#

我做到了:

  • proxy_set_header X-Real-IP $remote_addr;添加到nginx文件
  • 添加app.set('trust proxy', true)

My Express(v4.18.2)应用程序位于Nginx(v1.18.0 Ubuntu)之后,使用了上游块。它也是HTTPS连接。

因此,我认为建议的方法是可行的,但选择正确的方法来获取值仍然很棘手。
source code

相关问题