当从专用NIC访问时,Rails将IP显示为127.0.0.1,但Nginx显示正确的IP。公共IP转发正常 [英] Rails shows IP as 127.0.0.1 when accessed from private NIC, but Nginx shows the correct IP. Public IP gets forwarded fine
问题描述
我们正在Unicorn + Nginx上运行Rails应用程序。服务器有两个我们使用的NIC。 eth0
处理公共互联网的请求, eth2
处理来自我们专用网络的请求。
We are running a Rails application on Unicorn + Nginx. The server has two NICs that we use. eth0
handles requests for the public internet, and eth2
handles requests from our private network.
当请求通过 eth0
时,nginx日志显示公共IP,Rails日志也显示此IP。但是,当请求通过 eth2
时,nginx日志会正确显示私有IP(例如 192.168.5.134
),但是Rails日志显示 127.0.0.1
。
When a request comes through eth0
, the nginx logs show the public IP, and the Rails logs also show this IP. However, when a request comes through eth2
, the nginx logs show the private IP correctly (e.g. 192.168.5.134
), but the Rails logs show 127.0.0.1
.
所以它似乎是上的公共请求eth0
正确设置 X-Forwarded-For
标头,但 eth2上的请求不会发生这种情况
。
So it seems like public requests on eth0
get their X-Forwarded-For
header set correctly, but this isn't happening for requests on eth2
.
我们的nginx配置非常基本:
Our nginx config is pretty basic:
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.xx
地址都是私有地址,所以从<$ c $中删除它们c> X-Forwarded_For 标题。
The issue was that Rails thinks any 192.168.x.x
address is a private address, so strips them from the X-Forwarded_For
header.
# 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
See the relevant Rails source here and here.
一种解决方案是将其添加到 config / application.rb
:
One solution is to add this to your config/application.rb
:
config.action_dispatch.trusted_proxies = /^127\.0\.0\.1$/ # localhost
这样,本地网络上的IP将不会被'127.0.0.1'取代。
That way, IPs on your local network will not be replaced by '127.0.0.1'.
这篇关于当从专用NIC访问时,Rails将IP显示为127.0.0.1,但Nginx显示正确的IP。公共IP转发正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!