NGinx $ proxy_add_x_forwarded_for和real_ip_header

pie*_*ier 25 nginx http-headers

我在NGinx下有一个webapp和另一个正面负载均衡器,如下所示(xxxx = IP地址):

客户端(aaaa) - > LB(bbbb) - > NGX(cccc) - > WEBAPP(dddd)

这是我的NGinx配置的片段:

location / {
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header  X-Real-IP       $remote_addr;
    real_ip_header    X-Forwarded-For;
    set_real_ip_from  b.b.b.b;
    real_ip_recursive on;
}
Run Code Online (Sandbox Code Playgroud)
  1. 负载均衡器添加X-Forwarded-For客户端IP
    X-Forwarded-For=的字段a.a.a.a
  2. nginx的搜索客户端的真实IP X-Forwarded-For报头由omiting LB IP( b.b.b.b)和变化$remote_addr,从b.b.b.ba.a.a.a这样proxy_set_header X-Real-IP $remote_addr成真(OK这就是我想要的!)
    ,但也Nginx的完整的X-Forwarded-For报头与a.a.a.aIP代替b.b.b.b
  3. WEBAPP收到以下标题:
    X-Forwarded-For= a.a.a.a, a.a.a.a
    X-Real-IP= a.a.a.a
    - > X-Forwarded-For应该是a.a.a.a, b.b.b.b

我需要的是能够先设置proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for然后搜索真实IP并替换$remote_addr值.

任何人都可以帮我解决这个问题?

小智 15

the $proxy_add_x_forwarded_for is equal to "$http_x_forwarded_for,$remote_addr", and the $remote_addr variable will be changed when http_realip_module is using, so you will not get the last proxy addr in that header, changing the order of directives won't effect because they just change the options which determine how nginx handle the requests.

while http_realip_module is using, the $realip_remote_addr variable can be used as the real connected remote address, you can set your x-forwarded-for header like this:

proxy_set_header X-Forwarded-For "$http_x_forwarded_for, $realip_remote_addr";
Run Code Online (Sandbox Code Playgroud)

explanation of $realip_remote_addr variable

  • 请为您的答案提供更多背景信息,为什么您的答案有效?答案应该清楚,完整,并回答问题 (2认同)

小智 4

这里同样的问题。这很烦人,我实际上不确定这是功能还是错误:)

我知道这不是一个解决方案,但我删除了real_ip_header,并简单地使用X-Forwarded-For first ipaddress 在我需要的地方获取客户端的 IP 地址(例如日志)。