Servers Useful

How to use Cloudflare CF-IPCountry Hader in .htaccess !

The CF-IPCountry header is specific only to those who use Cloudflare in “Proxied” mode, so if you do not use Cloudflare, then this article is not useful!

1). How to block traffic from specific countries using CloudFlare

If for any reason you want to block visitors from any country, the solution is extremely simple and everything can be done from .htaccess file, via apache server:

# Block countries - IP Geolocation
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP:CF-IPCountry} ^(CN|IR|PK|TH|BD)$
RewriteRule ^ - [F,L]

Personally, I use the above .htaccess code in all my sites, possibly with some variations, depending on the target/niche. I chose these country not by random, but following the statistical analyzes on the major traffic, a lot of visits without any real conversion, because 99% are in fact bots that only look for vulnerabilities or duplicate my sites!

2). Deny POST request from all countries except on, my country

Another possibility of use for the CF-IPCountry header is present in the following example, where I filtered the access to the POST method for any country except my country, Romania:

# Block POST REQUEST from all conutry except my country
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP:CF-IPCountry} !^(RO)$
RewriteRule ^ - [F,L]

A very useful solution, considering that most attacks target vulnerabilities that allow later uploading files to the site to compromise it and take control, and in most cases the POST access method is essential!

Note: Of course, this example is not useful if you have a website with registered users, because their access will be blocked if they are from other countries!

In fact, you should know that this solution can prevent users who use VPN to access your sites. 

So pay close attention to using this example!


Leave a Reply

Your email address will not be published. Required fields are marked *