How to Pass Real IP Through Proxy in Nginx
To pass the real client IP through a proxy in
nginx, use the real_ip_header directive to specify the header carrying the original IP (usually X-Forwarded-For or X-Real-IP). Also, configure set_real_ip_from with the proxy server's IP to trust it and enable real_ip_recursive on; if there are multiple proxies.Syntax
The main directives to pass the real IP through a proxy in nginx are:
set_real_ip_from <trusted_proxy_ip>;- Defines trusted proxy IPs that can send the real client IP.real_ip_header <header_name>;- Specifies which header contains the original client IP.real_ip_recursive on|off;- Enables recursive search for the real IP in headers when multiple proxies are involved.
nginx
set_real_ip_from 192.168.1.1;
real_ip_header X-Real-IP;
real_ip_recursive on;Example
This example shows how to configure nginx to trust a proxy at IP 10.0.0.1 and extract the real client IP from the X-Forwarded-For header.
nginx
http {
real_ip_header X-Forwarded-For;
set_real_ip_from 10.0.0.1;
real_ip_recursive on;
server {
listen 80;
location / {
proxy_pass http://backend;
# Now $remote_addr will hold the real client IP
}
}
}Common Pitfalls
Not trusting the proxy IP: If you don't set set_real_ip_from to the proxy's IP, nginx will ignore the header and keep the proxy IP as the client IP.
Wrong header name: Using the wrong header (like X-Real-IP instead of X-Forwarded-For) will cause nginx to not get the real IP.
Multiple proxies without real_ip_recursive on;: If there are several proxies, you must enable recursive lookup to get the original client IP.
nginx
## Wrong way (missing set_real_ip_from)
real_ip_header X-Forwarded-For;
## Right way
set_real_ip_from 10.0.0.1;
real_ip_header X-Forwarded-For;
real_ip_recursive on;Quick Reference
| Directive | Purpose |
|---|---|
| set_real_ip_from | Trust this proxy IP to provide real client IP |
| real_ip_header | Header name carrying the original client IP |
| real_ip_recursive on|off | Enable recursive search for real IP through multiple proxies |
Key Takeaways
Always set
set_real_ip_from to the proxy IP to trust its headers.Use
real_ip_header to specify which header holds the real client IP.Enable
real_ip_recursive on; if multiple proxies are involved.Without proper configuration,
nginx will log the proxy IP instead of the real client IP.Check your proxy to confirm which header it uses to forward the client IP.