How to get real client IP in the REMOTE_ADDR in PHP Apache when using NGINX proxy?

666 Views Asked by At

I have recently switched to VestaCP using Apache with a NGINX reverse proxy. Very soon I noticed that all incoming traffic was logged as the server IP address. This being that Apache only sees the IP address of the NGINX proxy server, being my own server IP.

Using phpinfo() I can verify that the client IP is correctly forwarded in the HTTP_X_FORWARDED_FOR and the HTTP_X_REAL_IP, however it is not correctly added to the REMOTE_ADDR.

I have already tried to ensure the IP is correctly forwarded from NGINX to Apache by adding the following in the NGINX config files:

fastcgi_param REMOTE_ADDR $http_x_real_ip;

and

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

It definitely is the right direction as I can see the value $_SERVER['HTTP_X_REAL_IP'] is showing the correct IP address. However, this does not seem to do anything at all for the $_SERVER['REMOTE_ADDR'].

I also came across some other vague suggestions such as setting the IP address manually but this never did anything:

set_real_ip_from   192.168.122.1;

I cannot simply use $_SERVER['HTTP_X_REAL_IP'] as I use a framework where its hard-coded to use $_SERVER['REMOTE_ADDR'].

1

There are 1 best solutions below

0
On

To get this to work, I did the following:

  1. I installed the Apache remoteip module using the following command:

    sudo a2enmod remoteip &&  systemctl restart apache2
    
  2. In the /etc/nginx/nginx.conf I made sure the following line was added in the http {} block

    proxy_set_header    X-Client-IP       $remote_addr;
    
  3. I then added the following block of code to my /home/admin/conf/web/sitename.apache2.conf based on the Apache documentation

    <IfModule mod_remoteip.c>
    RemoteIPHeader X-Client-IP
    </IfModule>
    

Making sure that both the NGINX (step 2) and Apache (step 3) both use the exact same variable name X-Client-IP seems to have done the trick.

Now it populated the REMOTE_ADDR correctly using the forwarded client IP address.