0
0
NginxHow-ToBeginner · 3 min read

How to Use X-Forwarded-For Header in Nginx

To use the X-Forwarded-For header in Nginx, configure the real_ip_header X-Forwarded-For; directive and specify trusted proxy IPs with set_real_ip_from. This allows Nginx to log and use the original client IP instead of the proxy's IP.
📐

Syntax

The main directives to use the X-Forwarded-For header in Nginx are:

  • set_real_ip_from <proxy_ip>; - Defines trusted proxy IP addresses or ranges.
  • real_ip_header X-Forwarded-For; - Tells Nginx to use the X-Forwarded-For header for the client IP.
  • real_ip_recursive on; (optional) - Enables recursive search in X-Forwarded-For if there are multiple proxies.
nginx
set_real_ip_from 192.168.0.0/24;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
💻

Example

This example configures Nginx to trust a proxy at IP 10.0.0.1 and use the X-Forwarded-For header to get the real client IP for logging and access control.

nginx
http {
    set_real_ip_from 10.0.0.1;
    real_ip_header X-Forwarded-For;
    real_ip_recursive on;

    server {
        listen 80;

        location / {
            # Log the real client IP
            access_log /var/log/nginx/access.log combined;
            return 200 "Your IP is $remote_addr\n";
        }
    }
}
Output
Your IP is 203.0.113.45
⚠️

Common Pitfalls

Common mistakes when using X-Forwarded-For in Nginx include:

  • Not specifying trusted proxy IPs with set_real_ip_from, which can allow spoofed IPs.
  • Forgetting real_ip_recursive on; when multiple proxies add IPs to the header.
  • Using X-Forwarded-For without a proxy actually setting it, resulting in wrong IPs.
nginx
## Wrong (no trusted proxy):
real_ip_header X-Forwarded-For;

## Right:
set_real_ip_from 10.0.0.1;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
📊

Quick Reference

DirectivePurpose
set_real_ip_from Trust this proxy IP or subnet to provide real client IP
real_ip_header X-Forwarded-ForUse the X-Forwarded-For header as client IP
real_ip_recursive onEnable recursive search in X-Forwarded-For for multiple proxies

Key Takeaways

Always specify trusted proxy IPs with set_real_ip_from to avoid IP spoofing.
Use real_ip_header X-Forwarded-For to get the original client IP behind proxies.
Enable real_ip_recursive on if multiple proxies add IPs to the X-Forwarded-For header.
Without proper configuration, Nginx logs and uses the proxy IP instead of the client IP.
Test your setup by checking $remote_addr in logs or responses to confirm the real client IP.