当从私有NIC访问时,Rails显示IP为127.0.0.1,但Nginx显示正确的IP.公共 IP 可以正常转发



我们正在Unicorn + Nginx上运行一个Rails应用程序。服务器有两个我们使用的 NIC。 eth0处理对公共互联网的请求,eth2处理来自我们专用网络的请求。

当请求通过eth0时,nginx日志显示公共IP,Rails日志也显示此IP。但是,当请求通过eth2时,nginx日志会正确显示私有IP(例如 192.168.5.134 ),但 Rails 日志显示127.0.0.1

因此,似乎eth0上的公共请求正确设置了其X-Forwarded-For标头,但这不会发生在eth2上的请求中。

我们的nginx配置非常基本:

upstream example.com {
  server unix://var/www/example.com/shared/sockets/unicorn.socket fail_timeout=0;
}
...
server {
  listen 443 ssl;
  ...
  location @example.com  {
    proxy_set_header X-Forwarded-Proto $scheme;
    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_redirect off;
    if ($host ~* "^(.+).example.com$") {
      set $subdomain $1;
    }
    proxy_pass http://example.com;
  }

有什么想法吗?

问题是 Rails 认为任何192.168.x.x地址都是私有地址,因此将它们从 X-Forwarded_For 标头中删除。

# IP addresses that are "trusted proxies" that can be stripped from
# the comma-delimited list in the X-Forwarded-For header. See also:
# http://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces
TRUSTED_PROXIES = %r{
  ^127.0.0.1$                | # localhost
  ^(10                          | # private IP 10.x.x.x
    172.(1[6-9]|2[0-9]|3[0-1]) | # private IP in the range 172.16.0.0 .. 172.31.255.255
    192.168                      # private IP 192.168.x.x
   ).
}x

在此处和此处查看相关的 Rails 源代码。

一种解决方案是将其添加到您的config/application.rb

config.action_dispatch.trusted_proxies = /^127.0.0.1$/ # localhost

这样,本地网络上的 IP 就不会被"127.0.0.1"替换。

最新更新