16 Sep 2010

Setting up Geolocation with Maxmind's Apache Module

Geolocation
You have several options if you're trying to setup geolocation on your website. Geolocation allows you to determine where the user is most likely connecting from (Country, City etc) based on their IP address. Maxmind provides a decently accurate (99.5%) database and modules for free that you can setup pretty quickly on your server.

I am assuming you have PHP and Apache 2.x+ installed

To begin, log into your server and run the following commands:

cd /tmp
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
gunzip GeoIP.dat.gz
wget http://geolite.maxmind.com/download/geoip/api/c/GeoIP.tar.gz
tar -xzvf GeoIP.tar.gz
cd GeoIP-*
./configure
make
sudo make install
cd ..
cp GeoIP.dat /usr/local/share/GeoIP/GeoIP.dat
wget http://geolite.maxmind.com/download/geoip/api/mod_geoip2/mod_geoip2_1.2.5.tar.gz
tar -xzvf mod_geoip2_1.2.5.tar.gz
cd mod_geoip2_1.2.5
apxs -i -a -L/usr/local/lib -I/usr/local/include -lGeoIP -c mod_geoip.c

 

Next you'll need to open your apache config file (either apache.conf or httpd.conf). Try

/etc/httpd/conf/httpd.conf

or

/etc/apache2/apache2.conf

 

You'll need to add this somewhere at the end:

GeoIPEnable On
GeoIPDBFile /usr/local/share/GeoIP/GeoIP.dat MemoryCache
GeoIPOutput Env

Now just restart apache using one of these commands (whichever one applies to you):

sudo apachectl restart
sudo /etc/init.d/httpd restart
sudo /etc/init.d/apache2 restart

And do a quick test by creating a new php script with the following code:

<?php
print_r($_SERVER);
?>

You should see new GEOIP variables that will tell you what country the user is in:

Array
(
   [GEOIP_ADDR] => 74.59.82.169
   [GEOIP_CONTINENT_CODE] => NA
   [GEOIP_COUNTRY_CODE] => CA
   [GEOIP_COUNTRY_NAME] => Canada
...

There you go, you can now use

$_SERVER['GEOIP_COUNTRY_CODE']

in PHP to redirect the user based on the country they're connecting from.