21 November 2026 · 2 min read
Hardening Nginx behind Cloudflare
#security#nginx
Putting Cloudflare in front of a server gives strong protection, but the origin still needs locking down. If an attacker finds your real server IP, all of that protection can be bypassed. These are the steps I apply to every server.
1. Recover the real visitor IP
Behind Cloudflare, nginx only sees Cloudflare addresses. Trust only Cloudflare's IP ranges and read the CF-Connecting-IP header.
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 103.21.244.0/22;
real_ip_header CF-Connecting-IP;
The full list of ranges is published on Cloudflare's website and should be refreshed periodically.
2. Close direct access to the origin
- Allow ports 80 and 443 only from Cloudflare IP ranges in the firewall.
- Or use Cloudflare Tunnel so the origin opens no ports at all.
- Use the Full (strict) SSL mode with an origin certificate.
3. Security headers and rate limits
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
location = /login {
limit_req zone=login burst=5 nodelay;
}
4. Hide what is not needed
- Turn off
server_tokensso the nginx version is not exposed. - Deny access to hidden files such as
.envand.git. - Restrict admin panels and phpMyAdmin by IP or Cloudflare Access.
Wrapping up
Layered security works because each layer covers gaps in the others: a WAF at the edge, a firewall on the host, and a strict nginx configuration. Add monitoring for spikes in 403 and 429 responses as an early sign that someone is probing.