CloudflareHow Tolinuxupdate

How to block direct access to Cloudflare protected sites with .htaccess

Require visitors to use Cloudflare to access your site. IPs correct as of 23rd Oct 2020.

Note: we’d highly recommend using a hard firewall and requiring traffic to come via Cloudflare that way, but not everybody has that kind of access. This method still allows traffic to reach the server from outside of Cloudflare’s network, but Apache will then deny access to the site. This will still use up server bandwidth and does not prevent DoS/DDoS.

Using Cloudflare allows you to protect your site with products such as Cloudflare Access, or Cloudflare firewall rules, and Cloudflare DDoS protection. When Cloudflare protection is enabled, DNS queries for your domain will show Cloudflare IP addresses instead of your server’s real one. However, if somebody knows your server’s IP address they can bypass any of the protection you put in place. As mentioned earlier, we’d recommend a better method of forcing all users to come via Cloudflare, but this method may be the only option for shared hosting customers.

Cloudflare publish a list of IP addresses on their site and we’d recommend using the IPs in that list instead of just copying and pasting the content below. You can access the list here: https://www.cloudflare.com/en-gb/ips

Update 2021.04.08: List updated. 104.16.0.0/12 removed, 104.16.0.0/13 and 104.24.0.0/14 added.

To require visitors to be accessing your site via Cloudflare, add this to the .htaccess file at the root of your site (you can add your own IP address to the list to allow yourself to bypass Cloudflare, just add a new line before </FilesMatch> with Require ip <your IP>):

<FilesMatch .*>
Require ip 173.245.48.0/20
Require ip 103.21.244.0/22
Require ip 103.22.200.0/22
Require ip 103.31.4.0/22
Require ip 141.101.64.0/18
Require ip 108.162.192.0/18
Require ip 190.93.240.0/20
Require ip 188.114.96.0/20
Require ip 197.234.240.0/22
Require ip 198.41.128.0/17
Require ip 162.158.0.0/15
Require ip 104.16.0.0/13
Require ip 104.24.0.0/14
Require ip 172.64.0.0/13
Require ip 131.0.72.0/22
Require ip 2400:cb00::/32
Require ip 2606:4700::/32
Require ip 2803:f800::/32
Require ip 2405:b500::/32
Require ip 2405:8100::/32
Require ip 2a06:98c0::/29
Require ip 2c0f:f248::/32
</FilesMatch>

Jonathan Procter

Linux, Unix, and Windows server sysadmin.

Related Articles

Back to top button