Egg: 应用跑在nginx后面,我通过设置header拿到真实ip,有官方方法解决这个么?

Created on 4 Sep 2017  ·  10Comments  ·  Source: eggjs/egg

现在是在nginx里面把真实ip放在headers,然后在控制器里去取出来,有没有办法我在nginx设置某个特定的header,然后配置一下,覆盖掉req.ip

Most helpful comment

@THaGKI9 @atian25 @fengmk2 感谢大家的帮助问题解决了

  1. 只要在egg的config里面设置
config.proxy = true
  1. #nginx配置
upstream app_yourdomain {
    server 127.0.0.1:7070;
}

server {
    listen 8181;

    # pass the request to the node.js server with the correct headers
    # and much more can be added, see nginx config options
    location / {
      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://app_yourdomain/;
      proxy_redirect off;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
    }
 }

All 10 comments

自己写个中间件处理一下吧

@THaGKI9 没办法的话,只能这样了谢谢哈

config.proxy = true 即可,Nginx 反代的 headers 是有通俗约定的,这段处理在 koa 源码里

发自我的 iPhone

在 2017年9月4日,23:29,chenLX notifications@github.com 写道:

@THaGKI9 没办法的话,只能这样了谢谢哈


You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub, or mute the thread.

@atian25 他是想要一个自己定义一个 header...

有标准为啥要自定义

发自我的 iPhone

在 2017年9月5日,00:00,Tony Hawking notifications@github.com 写道:

@atian25 他是想要一个自己定义一个 header...


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub, or mute the thread.

应用层写一个 extend/request.js,覆盖度 ip getter 就可以实现了。 https://github.com/eggjs/egg/blob/master/app/extend/request.js#L107

我又重新看了源代码,原来 egg 已经将这个逻辑做成可配置的了,请将你的应用配置设置到 https://github.com/eggjs/egg/blob/master/config/config.default.js#L66 这里即可。改成你想要的 header,默认是 x-forwarded-for

@THaGKI9 @atian25 @fengmk2 感谢大家的帮助问题解决了

  1. 只要在egg的config里面设置
config.proxy = true
  1. #nginx配置
upstream app_yourdomain {
    server 127.0.0.1:7070;
}

server {
    listen 8181;

    # pass the request to the node.js server with the correct headers
    # and much more can be added, see nginx config options
    location / {
      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://app_yourdomain/;
      proxy_redirect off;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
    }
 }

可以看下 @fengmk2 给的那个链接,一般这几个 headers 都可以顺便一起在 nginx 配了。

我们文档可以加一个 nginx 反向代理的配置

Was this page helpful?
0 / 5 - 0 ratings