Redirecting EU visitors in Apache

At $work a client requested the ability to easily detect visitors to their site coming from within the EU so that they could redirect them accordingly.

Fortunately, this was pretty simple to do via use of mod_maxminddb which parses maxmind databases to provide a rather large amount of possible information.

You should follow the guide within their git to get it installed and acquire a maxmind database, of which both free and commerical copies exist, linked to on the module's git page.

Once installed and correctly using your maxmind DB within the apache config, we want to set it to both detect your visitor's country ISO code and from there check if they're within the EU. To grab their ISO code you would specify the following in your apache config:

MaxMindDBEnv MM_COUNTRY_CODE COUNTRY_DB/country/iso_code

This will create an apache variable called MM_COUNTRY_CODE which contains the 2 letter ISO code of your visitor. From this we can set another variable if this is code matches a defined EU state, like so:


So when you're done, your httpd.conf should contain lines that look like this:

MaxMindDBEnable On
MaxMindDBFile COUNTRY_DB /usr/local/share/GeoIP/GeoLite2-Country.mmdb
MaxMindDBFile CITY_DB    /usr/local/share/GeoIP/GeoLite2-City.mmdb
MaxMindDBEnv MM_COUNTRY_CODE COUNTRY_DB/country/iso_code

This can now be used within your .htaccess file to redirect customers who are in the EU as follows:

RewriteEngine On
RewriteCond %{ENV:EUROPEANUNION} ^1$
RewriteRule ^(.*)$ [R=301,L]