Thr*_*ark 11 nginx unicorn ruby-on-rails-3
我检查控制器中的ip-address
request.env['REMOTE_ADDR']
Run Code Online (Sandbox Code Playgroud)
这在我的测试环境中工作正常.但是在使用nginx + unicorn的生产服务器上,我总能得到127.0.0.1.
这是我的网站的nginx配置:
upstream unicorn {
server unix:/tmp/unicorn.urlshorter.sock fail_timeout=0;
}
server {
listen 80 default deferred;
# server_name example.com;
root /home/deployer/apps/urlshorter/current/public;
location ^~ /assets/ {
gzip_static on;
expires max;
add_header Cache-Control public;
}
try_files $uri/index.html $uri @unicorn;
location @unicorn {
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;
proxy_pass http://unicorn;
}
error_page 500 502 503 504 /500.html;
client_max_body_size 4G;
keepalive_timeout 10;
}
Run Code Online (Sandbox Code Playgroud)
Bry*_*rns 17
我也遇到了麻烦; 我发现了这个问题,但另一个答案对我没有帮助.
我查看了Rails 3.2.8的Rack :: Request#ip的实现,看看它是如何决定说的; 让它使用通过环境传递的地址而不过滤掉我本地网络中的地址(它试图过滤出中间代理,但这不是我想要的),我不得不另外从我的nginx代理配置块设置HTTP_CLIENT_IP你已经拥有了什么(X-Forwarded-For也必须在那里工作!):
proxy_set_header CLIENT_IP $remote_addr;
Run Code Online (Sandbox Code Playgroud)
如果您使用,request.remote_addr您将获得您的Nginx代理.
要获取用户的真实IP地址,您可以使用request.remote_ip.
根据Rails的源代码,它会检查各种http标头,以便为您提供最相关的标头:在Rails 3.2或Rails 4.0.0.beta1中
答案就在您的配置文件中:)以下内容应该执行您想要的操作:
real_ip = request.headers["X-Real-IP"]
Run Code Online (Sandbox Code Playgroud)
更多信息:http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-headers
更新:正确的答案在另一个问题中:
或者在这个线程中:
剧透:
使用request.remote_ip