Nginx – How to deny all requests not from cloudflare

cloudflarenginx

I've recently gotten denial of service attacks from multiple proxy ips, so I installed cloudflare to prevent this. Then I started noticing that they're bypassing cloudflare by connecting directly to the server's ip address and forging the host header.

What is the most performant way to return 403 on connections that aren't from the 18 ip addresses used by cloudflare?
I tried denying all then explicitly allowing the cloudflare ips but this doesn't work since I've set it up so that CF-Connecting-IP sets the ip allow tests for.

I'm using nginx 1.6.0.

Best Answer

As described here, you can only allow ip addresses from cloudflare.

https://erichelgeson.github.io/blog/2014/01/18/whitelisting-cloudflare-in-nginx/

# https://www.cloudflare.com/ips
# IPv4
allow 103.21.244.0/22;
allow 103.22.200.0/22;
allow 103.31.4.0/22;
allow 104.16.0.0/12;
allow 108.162.192.0/18;
allow 131.0.72.0/22;
allow 141.101.64.0/18;
allow 162.158.0.0/15;
allow 172.64.0.0/13;
allow 173.245.48.0/20;
allow 188.114.96.0/20;
allow 190.93.240.0/20;
allow 197.234.240.0/22;
allow 198.41.128.0/17;

# IPv6
allow 2400:cb00::/32;
allow 2405:b500::/32;
allow 2606:4700::/32;
allow 2803:f800::/32;
allow 2c0f:f248::/32;
allow 2a06:98c0::/29;

deny all; # deny all remaining ips

Note that you will have to update this configuration every one in a while as Cloudflare's IP address ranges might change. To autogenerate this configuration you can use this script

Related Topic