Nginx real_ip_header and X-Forwarded-For seems wrong

Better Stack Team
Updated on November 23, 2023

When dealing with proxy servers and the X-Forwarded-For header in Nginx, it's essential to ensure the correct usage of the real_ip_header directive to accurately identify the client's IP address.

The X-Forwarded-For header is often used to pass the original client's IP address through proxies. However, this header can be modified or spoofed, making it unreliable for determining the true client IP. To correctly obtain the actual client IP address in Nginx when behind a proxy, the real_ip_header directive is used to specify the header containing the real client IP.

Here's an example of how you might set up real_ip_header in your Nginx configuration:

 
http {
    real_ip_header X-Forwarded-For;
    set_real_ip_from 10.0.0.0/8; # Replace with the IP range of your proxy server

    # Additional Nginx configuration
    # ...

    server {
        # Server block configuration
        # ...
    }
}

Explanation:

  • real_ip_header X-Forwarded-For; specifies that the X-Forwarded-For header contains the actual client's IP address.
  • set_real_ip_from defines the trusted addresses or IP ranges of your proxy servers. Replace 10.0.0.0/8 with the actual IP range of your proxy server. This setting ensures that Nginx considers these IPs as trusted sources and extracts the real client IP from the specified header.

By using real_ip_header along with set_real_ip_from, you tell Nginx to extract the client's actual IP address from the specified header (X-Forwarded-For) and trust the defined proxy servers' IP addresses to provide the correct client IP information.

Remember to replace the example IP range 10.0.0.0/8 with your actual trusted proxy's IP range.

After making changes, verify the Nginx configuration for syntax errors:

 
sudo nginx -t

If the syntax is okay, reload Nginx to apply the changes:

 
sudo systemctl reload nginx

Always test and validate that the configuration accurately retrieves the real client IP addresses when using a proxy setup.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github