Getting remote IP with PHP when using nginx as gateway

When you set up nginx as gateway, you have configuration something along the lines of this:

upstream incoming-address.com {
ip_hash;
server serving-server1.com:80;
server serving-server2.com:80;
}

server {
listen incoming-address.com:80;
server_name incoming-address.com;

location / {
proxy_pass http://incoming-address.com;
}

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

}

Previously without the gateway in between, whenever you wanted to get IP address of the user accessing your site you could use the pre-defined PHP variable $_SERVER['REMOTE_ADDR']. However, with the gateway in between this would now return the gateway IP.

In the nginx as gateway configuration example above this part in the server section is the part that sets the user’s IP forwarding to the web server:

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

The answer is: with this configuration above to get the user’s IP accessing your site through gateway instead of $_SERVER['REMOTE_ADDR'] you must use $_SERVER['HTTP_X_REAL_IP'].

Or you can re-assign the $_SERVER['REMOTE_ADDR'] parameter.

Leave a Reply