How to block by country using .htaccess?

by percy_bauch , in category: SEO , 7 months ago

How to block by country using .htaccess?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by terrence , 7 months ago

@percy_bauch 

To block traffic from specific countries using .htaccess, you can use the mod_geoip module in Apache. Here's how you can do it:

  1. First, make sure the mod_geoip module is installed and enabled on your Apache web server. You can check if it's enabled by running the following command:
1
sudo apache2ctl -M | grep geoip


If it's not enabled, you can enable it by running:

1
2
sudo a2enmod geoip
sudo service apache2 restart


  1. Next, you'll need a GeoIP database to match IP addresses to countries. You can download the GeoIP database from the MaxMind website.
1
2
wget https://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
gunzip GeoIP.dat.gz


  1. Move the GeoIP.dat file to a location accessible by your web server. For example, you can move it to /etc/GeoIP/GeoIP.dat:
1
2
sudo mkdir /etc/GeoIP
sudo mv GeoIP.dat /etc/GeoIP/GeoIP.dat


  1. Edit your .htaccess file and add the following code at the top:
1
2
3
4
5
6
7
8
GeoIPEnable On
GeoIPDBFile /etc/GeoIP/GeoIP.dat

SetEnvIf GEOIP_COUNTRY_CODE CN BlockCountry
SetEnvIf GEOIP_COUNTRY_CODE RU BlockCountry
Order allow,deny
Allow from all
Deny from env=BlockCountry


In the above example, we block traffic from China (CN) and Russia (RU). You can modify the SetEnvIf lines to add or remove countries as needed. You can find the appropriate two-letter country codes at the ISO 3166-1 alpha-2 country code list.

  1. Save the .htaccess file and restart your Apache web server:
1
sudo service apache2 restart


Now, any visitor from the blocked countries will receive a "403 Forbidden" error when trying to access your website.