Tested on Ubuntu 14 / Varnish 4
First install packages and libraries needed, you must use the varnish official repositories:
~ $ sudo apt-get install varnish varnish-dev git-core libgeoip-dev apt-transport-https libtool python-docutils automake make
Then download geoip vmod and compile it:
~ $ cd /usr/src/ ~ $ git clone https://github.com/varnish/libvmod-geoip ~ $ cd libvmod-geoip ~ $ ./autogen.sh ~ $ ./configure ~ $ make ~ $ make install
Vmod will be installed in /usr/lib/varnish/vmods/.
TIP: The geoip database from repositories is a little bit outdated, so you can download the MaxMind free database to get better results:
~ $ cd /usr/share/GeoIP/ ~ $ mv GeoIP.dat GeoIP.dat.old ~ $ wget -O GeoIP.dat.gz http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz ~ $ gunzip GeoIP.dat.gz
Now in order to use its functions, first import the module in default.vcl file:
import geoip;
Then configure vmod geoip in varnish for blocking by country, for example if you want block China and Russia, in vcl_recv add first:
set req.http.X-Country-Code = geoip.country_code("" + client.ip);
to set the country code, and then to ban the country(s):
if (req.http.X-Country-Code ~ "(CN|RU)" ) { return (synth(403, "Forbidden")); }
Now in vcl_synth, add something like this:
if (resp.status == 403) { synthetic( {"<!DOCTYPE html> <html> <head> <title>Forbidden</title> </head> <body> <h1>Forbidden</h1> </body> </html> "} ) };
Finally reload varnish:
~ $ /etc/init.d/varnish reload