Today we were asked how to further improve DDoS protection when using Cloudflare.
As many of you know Cloudflare is a reverse proxy which masks ( hides ) the public IP posted in the DNS ‘A’ Record. This forces all traffic to use the domain name and as the IP is unknown attackers cannot attack the IP as all traffic MUST go through Cloudflare. This is useful when using the excellent WAF ( Web Application Firewall ) that Cloudflare provides as well as Browser checking and many other useful features. We highly recommend Cloudflare and we feel all website should be using it.
What if someone already knows your IP or the IP has been discovered from other DNS records such as a mail server or other publicly accessible application ? Well this is where .htaccess comes in. Why can’t we just only allow Cloudflare IPs and block all others? Well we can. Below is the .htaccess rule you can use that will allow Cloudflare IPv4 & IPv6 addresses and block all other IPs. This will force malicious and normal traffic to go though Cloudflare as if they do not then there is no way they can access your website.
To use the below .htaccess rule first make sure you have a .htaccess file in your public html root directoy. If you do not have a .htaccess file you can simply create one.
>Copy and paste the below content into your .htaccess file.
<Files 403.shtml> order allow,deny allow from all </Files> # https://www.cloudflare.com/ips-v4 # https://www.cloudflare.com/ips-v6 deny from all allow from 184.108.40.206/22 allow from 220.127.116.11/22 allow from 18.104.22.168/22 allow from 22.214.171.124/12 allow from 126.96.36.199/18 allow from 188.8.131.52/22 allow from 184.108.40.206/18 allow from 220.127.116.11/15 allow from 18.104.22.168/13 allow from 22.214.171.124/20 allow from 126.96.36.199/20 allow from 188.8.131.52/20 allow from 184.108.40.206/22 allow from 220.127.116.11/17 allow from 18.104.22.168/21 allow from 2400:cb00::/32 allow from 2405:8100::/32 allow from 2405:b500::/32 allow from 2606:4700::/32 allow from 2803:f800::/32 allow from 2c0f:f248::/32 allow from 2a06:98c0::/29
Once you have pasted the above content in your .htaccess save
it and then all traffic that does not go through Cloudflare will be blocked which is what we want. This will allow Cloudflare to mitigate any DDoS attacks and protect your website and other web applications.