How to configure Nginx to pass client IP addresses to PHP-FPM?

To configure Nginx to pass client IP addresses to PHP-FPM, you will need to make some changes to your Nginx configuration file. Here's how you can do it:

  1. Open your Nginx configuration file. Depending on your Linux distribution, the file may be located in different directories. Commonly, it is located at /etc/nginx/nginx.conf or /etc/nginx/sites-available/default.

  2. Look for the http block in the configuration file. This is where you define global configuration settings for Nginx.

  3. Inside the http block, add the following line:

    real_ip_header X-Forwarded-For;

    This line tells Nginx to read the X-Forwarded-For header to obtain the client's IP address.

  4. Add the following line to specify the trusted proxy IP addresses:

    set_real_ip_from <proxy IP>;

    Replace <proxy IP> with the IP address of the proxy server. If you have multiple proxy servers, add multiple set_real_ip_from lines.

  5. Save the configuration file.

  6. Test the configuration to make sure there are no syntax errors:

    sudo nginx -t
  7. If the test is successful, reload the Nginx configuration to apply the changes:

    sudo systemctl reload nginx

Now, Nginx should forward the client's IP address to PHP-FPM in the $_SERVER['REMOTE_ADDR'] variable. You can verify this by checking the REMOTE_ADDR variable in your PHP application.