May 3, 2020

Using Cloudflare DNS with Nginx

Cloudflare is a service that provides us a network of proxy servers all over the world that cache content from your server and delivers it to your visitors from the closest server. This has a two-fold benefit. First, it speeds up the loading time for your website and improves your visitors experience. Second, it reduces the amount of outgoing traffic from your host server, thus reducing your bill for outgoing traffic.

Setting up Cloudflare is quite easy and the settings only involve changing the DNS settings with your DNS service or hosting provider to instead point to the DNS servers specified by Cloudflare when you sign up.

However, at times (for example when you implement access control to your website using IP allow/deny), you need the true IP from the visitor. Cloudflare forwards a copy of the visitors IP as part of the "CF-Connecting-IP" and "X-Forwarded-For" flags. You will need to restore the true IP from these flags in your Nginx configuration for your website, for your IP based service denial to work correctly. For this you can add to your config file

server {

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 104.16.0.0/12;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 131.0.72.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
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 2c0f:f248::/32;
set_real_ip_from 2a06:98c0::/29;

real_ip_header CF-Connecting-IP;
...
}

The "set_real_ip_from ..." specifies all the IPs of Cloudflare servers that are forwarding you the visitor requests. These IPs are regularly updated and listed on https://www.cloudflare.com/ips/. Apart from this you can refer to the following post on Cloudflare support to get details for equivalent configurations when using servers other than Nginx.

https://support.cloudflare.com/hc/en-us/articles/200170786-Restoring-original-visitor-IPs-Logging-visitor-IP-addresses-with-mod-cloudflare-#12345681