Block or redirect using mod_geoip

PDF

Installing mod_geoip allows you to block or redirect traffic based on the geografical location of the client using the IP-address of the client. mod_geoip for CentOS is available at the EPEL repository. If you haven't setup the EPEL repository follow the instructions explained on their website. I asume you allready installed Apache. Download and install mod_geoip, GeoIP and the related libraries:

yum install GeoIP GeoIP-devel GeoIP-data zlib-devel mod_geoip
As MaxMind regularly update their database files you might choose to download the file manually using by a cronjob. Create a bash script which download and install the GeoLite databases. This example is base on the GeoLite version, if you have a subscription your change the according lines to download the appropiate database files:
#!/bin/bash
#Download Maxmind GeoIP databases
cd /var/lib/GeoIP
mv GeoIP.dat GeoIP.dat.old
/usr/bin/wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
/usr/bin/wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
gunzip GeoIP.dat.gz
gunzip GeoLiteCity.dat.gz
Make this script executable:
chmod 750 SCRIPTNAME.SH
and edit your crontab to run this script every 3rd day of the month:
crontab -e
0 0 3 * * /PATH_TO_SCRIPT/SCRIPTNAME
Edit the configuration file /etc/httpd/conf.d/mod_geoip.confand activate the module and change the path of the database. (GeoLiteCity.dat also returns the CityNames and the geographic locations):
LoadModule geoip_module modules/mod_geoip.so
<IfModule mod_geoip.c>
GeoIPEnable On
GeoIPDBFile /var/lib/GeoIP.dat
</IfModule>
and restart Apache:
/ect/init.d/apache restart
Now create a .htaccess file. For example if you want to block clients from Russia and China:
SetEnvIf GEOIP_COUNTRY_CODE CN BlockCountry
SetEnvIf GEOIP_COUNTRY_CODE RU BlockCountry
Deny from env=BlockCountry
If you want to redirect based on the country using mod_rewrite in combination with mod_geoip, your .htaccess file could look like this:
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^(NL|BE)$
RewriteRule ^(.*)$ http://www.mydomain.com/nl/$1 [L]
For more example take a look at he website of MaxMind
 

Please login first before adding a comment.

Search






You are here: Home Howtos and FAQs Apache Block or redirect using mod_geoip