10

我们正在 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;
  }

有任何想法吗?

4

1 回答 1

7

问题是 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”替换。

于 2013-11-11T10:52:06.250 回答