ruby-on-rails - 从私有(private) NIC 访问时,Rails 显示 IP 为 127.0.0.1,但 Nginx 显示正确的 IP。公共(public) IP 可以正常转发

标签 ruby-on-rails networking nginx ip unicorn

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

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

所以看起来像是 eth0 上的公共(public)请求得到他们的X-Forwarded-For header 设置正确,但 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 address 是私有(private)地址,因此将它们从 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 源 herehere .

一种解决方案是将其添加到您的 config/application.rb :
config.action_dispatch.trusted_proxies = /^127\.0\.0\.1$/ # localhost

这样,您本地网络上的 IP 将不会被“127.0.0.1”替换。

关于ruby-on-rails - 从私有(private) NIC 访问时,Rails 显示 IP 为 127.0.0.1,但 Nginx 显示正确的 IP。公共(public) IP 可以正常转发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19871264/

相关文章:

ruby-on-rails - Rails协会has_one最新记录

c# - StorageException : Blob data corrupted. 收到的字节数不正确 - 这是我的代码中的错误还是 azure 服务器问题?

windows - 在 Linux VirtualBox 和 Windows 7 之间设置网络

java - 将 HTTP/2 从 h2 反向代理到 h2c

php - nginx : Resource interpreted as Stylesheet but transferred with MIME type text/html 无法识别 css 和图像

javascript - Ruby on Rails 与 Parse + Backbone.js

javascript - Rails 3.2,javascript 执行两次

django - Django Whitenoise缺点

ruby-on-rails - 我的 cookie token 是否足够强大,可以用于用户身份验证目的?

java - 如何测试 ipv6 地址是否与网络前缀匹配