Skip to content

Using mod_geoip in .htaccess

  • by

There has been some comments in my old posts trying to use generated country lists in Apache .htaccess. This approach is wrong, and I will show you much better way how to block or allow specific country.

I have already mentioned how to use Maxmind GeoIP database as alternative for generating country list. Original purpose of this db is to allow or deny some country in your application. There are plugins for apache2, nginx, proftpd, php and much more.

How to use it in .htaccess file instead of many IP address?

Install geoip database, on Debian (and clones)

apt-get install geoip-database

now install apache2 module and enable it

apt-get install libapache2-mod-geoip
a2enmod geoip

For Centos, module is available in EPEL repository. There is nice blog post how to install it.

Now create your .htaccess file. You can choose if Deny by default and Allow specific country:

GeoIPEnable On
SetEnvIf GEOIP_COUNTRY_CODE SK AllowCountry
SetEnvIf GEOIP_COUNTRY_CODE CZ AllowCountry
Deny from all
Allow from env=AllowCountry

or Allow by default and Deny specific country

GeoIPEnable On
SetEnvIf GEOIP_COUNTRY_CODE CN BlockCountry
SetEnvIf GEOIP_COUNTRY_CODE RU BlockCountry
# ... place more countries here
Deny from env=BlockCountry

This my blog is using Deny for wordpress login page from outside Slovakia and Czech republic:

GeoIPEnable On
SetEnvIf GEOIP_COUNTRY_CODE SK AllowCountry
SetEnvIf GEOIP_COUNTRY_CODE CZ AllowCountry
Deny from all
Allow from env=AllowCountry
#and also allow private ip from lan 
Allow from 10.0.0.0/8
Allow from 192.168.0.0/16

More examples are on Maxmind page.

One note at the end. If you install geoip-database-contrib package instead of geoip-database, it will install cron job in your server responsible for downloading and updating GeoIP database and your IP to country database will be always up to date.

Leave a Reply

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