In this forum, we will learn to block web traffic from a country on Apache web server using the .htaccess file.
There are two ways by which we can block web traffic in apache server from a country, either we can use the IP addresses to block web traffic or we can use the country codes to block traffic.
Block web traffic in Apache based on IP address
Using this way, we can also block traffic from any source & not only from a particular country. For this method to work, open the .htaccess file (usually located in the website document directory).
$ sudo vim /var/www/html/linuxtechlab/.htaccess
& make the following entries into the file,
Order allow,deny
Allow from all
Deny from 150.20.0.0/12
Deny from 191.16.0.0/16
Deny from 12.16.1.0/8
Here the IP address mentioned are from the country for which you need to block the web traffic. But this method has a downside when using it to block traffic from a country as we need to have all the IP addresses for that particular country. But we can generate the list of IP address used by a country from this website.
Block web traffic in Apache based on Country code
This method is much more easy method to block the web traffic originating from a particular country as we only need the country code & not the list of IP addresses to block the traffic.
We can get the country code list from the following website. Once you the country make the following entry to the .htaccess file,
$ sudo vim /var/www/html/linuxtechlab/.htaccess
SetEnvIf CF-IPCountry DE BuzzOff=1
Order allow,deny
Allow from all
Deny from env=BuzzOff
Here, we have used the country code ‘DE’ which is the country code for Germany. Similarly we can block the traffic from more than once country,
SetEnvIf CF-IPCountry DE BuzzOff=1
SetEnvIf CF-IPCountry CN BuzzOff=1
SetEnvIf CF-IPCountry IN BuzzOff=1
SetEnvIf CF-IPCountry FR BuzzOff=1
SetEnvIf CF-IPCountry GR BuzzOff=1
Order allow,deny
Allow from all
Deny from env=BuzzOff
Here, we have blocked traffic from Germany, China, India, France & Greece.
====================================================================================================