8

My server doesn't have a public IP address, so I don't know how to get the real client's IP address.

This is my nginx's configuration:

location / {
    proxy_pass http://domain1;
    proxy_set_header        Host            $host;
    proxy_set_header        X-Real-IP     $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
}

In my Rails app's controller both request.ip and request.remote_ip return my server's gateway address.

How can i get the real IP of client?

How to get X-Forwarded-For value from Rails request?

2 Answers 2

21

Rails was supposed to be doing it automatically for us, but it seems to be broken with current 3.x

I'm using this:

def ip() request.env['HTTP_X_FORWARDED_FOR'] || request.remote_ip end
2
  • How do I detect request from localhost? Before nginx I used to get 127.0.0.1, but now I get the private IP address instead...
    – Adrian
    Nov 4, 2014 at 15:18
  • A reminder that the header is not necessarily an IP but more specifically a list of IPs separated by commas, the left most being the original client. If there's only one IP, the above code will work but I suspect not if there were more than one. See en.wikipedia.org/wiki/X-Forwarded-For. Aug 16, 2017 at 16:59
6

You should get the header value X-forwarded-for

http://en.wikipedia.org/wiki/X-Forwarded-For

7
  • 1
    It may not be the "REAL" ip of client if he is sitting behind proxy :) and you know :) May 26, 2011 at 14:09
  • 1
    @Rizwan Sharif then we simply consider the proxy is the client. ^^
    – user142019
    May 26, 2011 at 14:12
  • 1
    but the IP in my rails's log is gate_way address also.
    – ethan
    May 26, 2011 at 16:02
  • 2
    Your gateway might be doing Source Nat. Where is nginx installed ? Behind gateway or on the same machine as gateway or same machine as apache ? May 26, 2011 at 17:01
  • 2
    I don't understand. Does the question not show that he is trying to get the X-Forwarded-For header value but the answer states that he should do it. Is the attempt in the question wrong?
    – atw
    Mar 10, 2015 at 11:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.