NoCache

Table of Contents

Restore Real IP Address From Cloudflare CDN in Nginx

Cyrus Kao
Last modified on .

Cloudflare CDN works just like a reverse proxy, it sits in front of your web servers and forwards client requests to them. So the requests reaching your server actually came from Cloudflare. To restore the original client's IP address, we'll be using ngx_http_realip_module in Nginx to retrieve them from headers.

Finds Out Cloudflare's IP Ranges

In order to trust the requests from a proxy, we must find out Cloudflare's IP ranges at the official site or by API:

IP ranges
Cloudflare's IP ranges

Configure Nginx

Create a set_real_ip_from directive for each IP range, and real_ip_header to restore the real IP address from Cloudflare's header CF-Connecting-IP:

http {
	# IPv4
  set_real_ip_from 173.245.48.0/20;
  set_real_ip_from 103.21.244.0/22;
  set_real_ip_from 103.22.200.0/22;
  set_real_ip_from 103.31.4.0/22;
  set_real_ip_from 141.101.64.0/18;
  set_real_ip_from 108.162.192.0/18;
  set_real_ip_from 190.93.240.0/20;
  set_real_ip_from 188.114.96.0/20;
  set_real_ip_from 197.234.240.0/22;
  set_real_ip_from 198.41.128.0/17;
  set_real_ip_from 162.158.0.0/15;
  set_real_ip_from 104.16.0.0/13;
  set_real_ip_from 104.24.0.0/14;
  set_real_ip_from 172.64.0.0/13;
  set_real_ip_from 131.0.72.0/22;
	# IPv6
  set_real_ip_from 2400:cb00::/32;
  set_real_ip_from 2606:4700::/32;
  set_real_ip_from 2803:f800::/32;
  set_real_ip_from 2405:b500::/32;
  set_real_ip_from 2405:8100::/32;
  set_real_ip_from 2a06:98c0::/29;
  set_real_ip_from 2c0f:f248::/32;

	real_ip_header CF-Connecting-IP;
	...
}
Nginx config

set_real_ip_from and real_ip_header are allowed in http, server, location blocks.

Reload Nginx after it's configured:

$ sudo nginx -s reload

Verify IP Address is Real

Check your access_log for the incoming IP addresses:

$ less /var/log/nginx/access.log
...
2001:b011:e601:232d:xxxx:xxxx:xxxx:xxxx - - [18/Jan/2022:05:13:07 +0000] "GET / HTTP/2.0" 200 9894 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36"
Output

Comments

Sign in to leave a comment.