Recently, while building a logging class to be used on all my php REST/JSON and SOAP webservices, I came across an issue when reading the REMOTE_ADDR server variable.

When using Nginx, the $_SERVER[‘REMOTE_ADDR’] variable comes, by default, with the IP Address of the Nginx machine, which makes sense, if you think about it. Meaning, in a scenario like the following, every single request hitting Nginx, will be forwarded to one of the nodes with the REMOTE_ADDR variable filled with the value 172.20.0.10.

 

Nginx
172.20.0.10

Node 1
172.20.0.11

Node 2
172.20.0.12

Now, what I wanted was a way to know the client real IP address, which means, on the scenario I mentioned above, if I call a webservice from my computer, the IP address read from my scripts will be 10.104.3.88 instead of 172.20.0.10. But how?

There are several of websites giving you a way of accomplishing this by installing a mod on Apache called mod_rpaf (Reverse Proxy Add Forward) but this mode is not available on the default repositories which makes me unsure on having this running on my server. I want something more transparent.

Solution:

Edit your nginx.conf located on /etc/nginx/ and add the following line:

proxy_set_header        X-Real-IP       $remote_addr;

Basically, adds the X-REAL-IP header containing the client ip address.

Reload Nginx, and run the following piece of php code:

<?php echo $_SERVER[‘HTTP_X_REAL_IP’] ?>

 

Reference

My thread on the official Nginx Forums: http://forum.nginx.org/read.php?11,231704