How to Use X-Real-IP Header in Nginx for Client IP
To use
X-Real-IP in Nginx, enable the real_ip_module and configure set_real_ip_from with trusted proxy IPs, then use real_ip_header X-Real-IP; to tell Nginx to trust that header as the client IP. This helps Nginx log and process the actual client IP when behind proxies.Syntax
The main directives to use X-Real-IP in Nginx are:
set_real_ip_from <trusted_proxy_ip>;- Defines IP addresses of trusted proxies that can send theX-Real-IPheader.real_ip_header X-Real-IP;- Specifies that Nginx should use theX-Real-IPheader as the client IP.
These directives must be placed in the http or server context.
nginx
http {
set_real_ip_from 192.168.1.0/24;
real_ip_header X-Real-IP;
# other config
}Example
This example shows how to configure Nginx to trust a proxy at IP 10.0.0.1 and use the X-Real-IP 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-Real-IP;
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-Real-IP in Nginx include:
- Not specifying
set_real_ip_fromfor trusted proxies, causing Nginx to ignore the header. - Trusting all IPs (e.g.,
0.0.0.0/0), which is a security risk because clients can spoof their IP. - Placing directives in the wrong context (they must be in
httporserverblocks).
Example of wrong and right usage:
nginx
# Wrong: Missing set_real_ip_from
http {
real_ip_header X-Real-IP;
}
# Right:
http {
set_real_ip_from 192.168.0.0/16;
real_ip_header X-Real-IP;
}Quick Reference
| Directive | Purpose |
|---|---|
| set_real_ip_from | Defines trusted proxy IPs allowed to set X-Real-IP |
| real_ip_header X-Real-IP; | Tells Nginx to use X-Real-IP header as client IP |
| real_ip_recursive on; | Optional: allows recursive search of real IP headers if multiple proxies |
| $remote_addr | Variable holding the client IP after real IP processing |
Key Takeaways
Always specify trusted proxy IPs with set_real_ip_from to securely use X-Real-IP.
Use real_ip_header X-Real-IP to tell Nginx to trust the X-Real-IP header for client IP.
Never trust all IPs (0.0.0.0/0) as it allows IP spoofing.
Place these directives inside the http or server block in your Nginx config.
Check $remote_addr to confirm Nginx uses the real client IP after configuration.