Nginx Allows Cloudflare Traffic Only


Get Cloudflare IP List:


Install Nginx extra module

sudo apt-get install nginx-extras


Configure nginx.conf

Create a file to store Cloudflare whitelisted IP list.

vim /etc/nginx/cloudflare-whitelist.conf

Use this command to get the IP list from Cloudflare.

{ curl -s "https://www.cloudflare.com/ips-v4"; echo ""; curl -s "https://www.cloudflare.com/ips-v6"; } | awk '{print "set_real_ip_from "$1";"}' && echo "real_ip_header CF-Connecting-IP;" && echo "" && echo "geo \$realip_remote_addr \$cloudflareips {" && echo "\tdefault 0;" && { curl -s "https://www.cloudflare.com/ips-v4"; echo ""; curl -s "https://www.cloudflare.com/ips-v6"; } | awk '{print "\t"$1" 1;"}' && echo "}"

cloudflare-whitelist.conf


Add the configuration file to /etc/nginx/nginx.conf:

vim /etc/nginx/nginx.conf
include /etc/nginx/cloudflare-whitelist.conf;

nginx.conf


Implement to Server Host / Virtual Host Configuration

Configure host file / virtual host file add this configuration below.

if ($cloudflareips != 1) {
	return 403;
}

host configuration


Restart!