How to Make Nginx Reveal Real Visitor IP Behind CDN in Just 2 Lines
After enabling a CDN or cloud firewall, your server only sees the CDN node’s IP, causing login risk, IP bans, fake logs, and difficulty tracing attacks; this guide shows how to add two Nginx directives to trust the X‑Forwarded‑For header and accurately capture the true client IP, with optional security recommendations.
Why does this problem appear?
CDN works as User → CDN node → Your server . Therefore the request reaching your server has the CDN node’s IP as the source, not the real user’s IP.
Fortunately, CDN adds the real IP in request headers, most commonly:
X-Forwarded-For: 223.104.18.99, 119.23.12.55 X-Real-IP: 223.104.18.99We need to tell Nginx to treat the first IP in X-Forwarded-For as the real visitor IP.
Solution (Nginx configuration)
Step 1: Modify Nginx configuration file
Baota users: go to Website → Settings → Configuration File . Other users: edit /etc/nginx/nginx.conf or the site’s configuration file.
In the http block (not the server block) add the following two lines:
# CDN get real IP
set_real_ip_from 0.0.0.0/0;
real_ip_header X-Forwarded-For;Configuration explanation: set_real_ip_from 0.0.0.0/0; This trusts all sources for the X-Forwarded-For header because CDN node IPs are not fixed.
In production replace 0.0.0.0/0 with the official IP ranges of your CDN provider for better security.
Example: Alibaba Cloud CDN IP ranges
set_real_ip_from 140.205.0.0/16;
set_real_ip_from 11.11.11.0/24;
set_real_ip_from 47.91.0.0/16;Cloudflare example (use CF-Connecting-IP header)
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 103.21.244.0/22;
# ... (full list on Cloudflare site)
real_ip_header CF-Connecting-IP;Step 2: Reload Nginx
Baota: click Reload Configuration .
Command line:
nginx -t && nginx -s reloadVerification
Access your site using a mobile 4G network (to avoid local interference) and check the access log (e.g., /www/wwwlogs/yourdomain.log). The logged IP should be your mobile’s public IP, not the CDN node IP. In PHP you can verify with: echo $_SERVER['REMOTE_ADDR']; The output should show the real IP.
Security advice (important!)
Using 0.0.0.0/0 is simple but risky because attackers can forge the X-Forwarded-For header.
Recommended practice: trust only the official IP ranges of the CDN you use.
Summary
With just two Nginx directives and a quick reload, you can obtain accurate visitor IP data, improving security protection and operational analysis.
Xiao Liu Lab
An operations lab passionate about server tinkering 🔬 Sharing automation scripts, high-availability architecture, alert optimization, and incident reviews. Using technology to reduce overtime and experience to avoid major pitfalls. Follow me for easier, more reliable operations!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
