ruby-on-rails – 当从私有NIC访问时,Rails显示IP为127.0.0.1,但Nginx显示正确的IP.公网IP转发正常

我们正在Unicorn Nginx上运行Rails应用程序.服务器有两个我们使用的网卡. 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源herehere.

一个解决方案是将其添加到你的config / application.rb中:

config.action_dispatch.trusted_proxies = /^127\.0\.0\.1$/ # localhost

这样,本地网络上的IP将不会被’127.0.0.1’所取代.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...