If you want to add some rules to your Apache based on the clients country, mod_geoip is perfect for it.
Installation
On Squeeze following is enough: # apt-get install libapache2-mod-geoip geoip-database/squeeze-backports
Note that you should use the geoip-database version from squeeze-backports to have got the most up to date database version, I am updating it every month.
Configuration
You can add the rules to your VirtualHost, Directory, Location directives and also to your apache2.conf (“serverwide”). So you are flexible with where to use it.
Blocking countries
On some servers I have got more than 90 percent of spam requests only from three countries, so I blocked them with:
<DirectoryMatch “^/var/www/.*/html”>
SetEnvIf GEOIP_COUNTRY_CODE RU BlockCountry
SetEnvIf GEOIP_COUNTRY_CODE CN BlockCountry
SetEnvIf GEOIP_COUNTRY_CODE UA BlockCountry
Deny from env=BlockCountry
</DirectoryMatch>
Allow only specific countries
In the other way you also can allow specific countries to have got access to your website, this also may be a good idea for extranets, where you know from where your customers are:
<Directory “/var/www/my.site.com/html/login”>
SetEnvIf GEOIP_COUNTRY_CODE DE AllowCountry
SetEnvIf GEOIP_COUNTRY_CODE CH AllowCountry
Deny from all
Allow from env=AllowCountry
</Directory>
Very easy!
Rewrite Rules
You can also use it for mod_rewrite. Within a project, customers from CN and TW should be redirected to the chinese page:
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^(CN|TW)$
RewriteRule ^(.*)$ http://some.example.cn/site.php [L]
mod_geoip with proxy frontends
Normaly mod_geoip works behinds load balancers and proxy servers, since it also take care of the HTTP_X_FORWARDED_FOR header.
But with haproxy it looks problematic, since it does not add the HTTP_X_FORWARDED_FOR header to KeepAlive’d requests :( Disabling KeepAlive is a bad idea on this cluster, so we decided to also use php5-geoip in our application, so everything is working nice now..
What mod_geoip is NOT is
mod_geoip helps you to block/allow specific countries, but it does not protect you from them.
Also keep in mind that the database is only ~ 99,8% accurate, so you may have got false positives/negatives. If you only allow german users, a german IP could be listed as russian.
This is much more problematic with mobile/satellite connections and surely you can also not access your page, if you are on vacation in another country. ;)