Installing and using libapache2-mod-geoip on Debian


 

Installation & Configuration:

Install the the needed packages:
apt-get update
apt-get install -y geoip-bin geoip-database libgeoip-dev libgeoip1 libapache2-mod-geoip 

The installation normally enables the new module directly. If this is not the case for whatever reason, just enabled it by executing: a2enmod geoip

Before restarting Apache, we need to adapt the module's configuration file /etc/apache2/mods-available/geoip.conf as follows:
<IfModule mod_geoip.c>
  GeoIPEnable On
  GeoIPDBFile /usr/share/GeoIP/GeoIP.dat
  GeoIPDBFile /usr/share/GeoIP/GeoIP.dat MemoryCache
  GeoIPDBFile /usr/share/GeoIP/GeoIP.dat CheckCache
  GeoIPScanProxyHeaders On
</IfModule>

Now restart Apache:
/etc/init.d/apache2 restart

 

Accessing using PHP:

In PHP you now should have these server variables:
GEOIP_ADDR
GEOIP_CONTINENT_CODE
GEOIP_COUNTRY_CODE
GEOIP_COUNTRY_NAME

You can put a little PHP script on your webserver to show them:
<?php
echo "Country: " . apache_note("GEOIP_COUNTRY_NAME");

or: 
<?php
echo "Country: " . $_SERVER["GEOIP_COUNTRY_NAME"];

The info script should show all available variables listed above:
<?php
echo phpinfo();

 

Blocking users:

Now you may want to create rules based on where your visitors come from. For example you may want to block users from a certain country. To block for example all users coming from Germany (well, bad example oubviously, adapt it to your needs), you would add this line to /etc/apache2/mods-available/geoip.conf:
SetEnvIf GEOIP_COUNTRY_CODE DE BlockCountry 

This sets an environment variable that you can use as follows in your virtual host configuration or in a htaccess (keep attention of your AllowOverride directive):
Order allow,deny
allow from all
Deny from env=BlockCountry