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 |
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
January 4, 2016 at 7:28 pm
I think this function is also a good soloution to find users real IP address.
function getrealip()
{
if (isset($_SERVER)){
if(isset($_SERVER[“HTTP_X_FORWARDED_FOR”])){
$ip = $_SERVER[“HTTP_X_FORWARDED_FOR”];
if(strpos($ip,”,”)){
$exp_ip = explode(“,”,$ip);
$ip = $exp_ip[0];
}
}else if(isset($_SERVER[“HTTP_CLIENT_IP”])){
$ip = $_SERVER[“HTTP_CLIENT_IP”];
}else{
$ip = $_SERVER[“REMOTE_ADDR”];
}
}else{
if(getenv(‘HTTP_X_FORWARDED_FOR’)){
$ip = getenv(‘HTTP_X_FORWARDED_FOR’);
if(strpos($ip,”,”)){
$exp_ip=explode(“,”,$ip);
$ip = $exp_ip[0];
}
}else if(getenv(‘HTTP_CLIENT_IP’)){
$ip = getenv(‘HTTP_CLIENT_IP’);
}else {
$ip = getenv(‘REMOTE_ADDR’);
}
}
return $ip;
}