Rails - how to obtain visitors' IP address?
When you visit a site locally you're coming from the local IP address, ie 127.0.0.1.
What you're doing is the correct way to the visitors IP address, and the result you're seeing is as expected.
You want to use
@ip = request.remote_ip
because that takes into account most cases of reverse proxies and other situations you might encounter where request.env['REMOTE_ADDR']
might be nil or the address of the local proxy.
If you indeed do have a reverse proxy in front of your application server (and you probably do), you need to make sure it sets the proper headers when forwarding the requests. As a minimum the X-Forwarded-For
header should be set.
Sample nginx configuration
If you're using nginx as a reverse proxy in front of your Rails application (ie using proxy_pass
), you need to configure it to add the proper headers to the request it sends. In the case of X-Forwarded-For
that is done using:
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
You might want to also configure the following to have nginx forward the requested hostname and protocols:
# enable this if you forward HTTPS traffic to Rails,# this helps Rack set the proper URL scheme for doing redirects:proxy_set_header X-Forwarded-Proto $scheme;# pass the Host: header from the client right along so redirects# can be set properly within the Rack applicationproxy_set_header Host $http_host;
x-forwarded-for. x-forwarded-for (XFF) is a standard proxy header which indicates the IP addresses that a request has flowed through on its way from the client to the server.
In my nginx server configuration I had,
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
I was getting client remote IP as below,
request.env['HTTP_X_FORWARDED_FOR'] || request.remote_ip
Note: It can be wrong IP address if client is sitting behind proxy.