Using GeoIP from within Nginx

WebSVN in Japanese
This is what it should look like if you are in Japan.

Since late last summer me and my friends have been experimenting with Nginx. It’s a neat little server, sublimely fast and it’s config format doesn’t make you wince. I use it especially for proxying dynamic content from other servers (like Mongrel) but it handles static content equally well.
I’ve played around with geolocation in most of my Rails apps and it made me think this sort of environmental information might just as well be managed by the server. The folks at MaxMind felt the same way, it seems. There are server-side modules available for Apache and Lighty. For Nginx it takes a little more effort, but it’s very doable. Let’s make it so!
Get the GeoLite CSV:

 $ wget http://www.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip

Unpack it:

 $ unzip GeoIPCountryCSV.zip

Get the Nginx tarball:

 $ wget http://sysoev.ru/nginx/nginx-0.5.35.tar.gz

Unpack it:

 $ tar zxvf nginx-0.5.35.tar.gz

You can also get Nginx through you package manager but mine (Debian) didn’t install the included Perl script to convert the MaxMind CSVfile. You can run the script on the CSV file you extracted by running it like so:

 $ perl ./nginx-0.5.35/contrib/geo2nginx.pl < GeoLiteCity_20080301/GeoLiteCity-Location.csv > countries.conf

This generates a countries.conf which Nginx can use. You have to include it in your nginx.conf. Here’s what I added to my nginx.conf in the http namespace. Before this step I moved the generated countries.conf file to my /etc/nginx directory.

geo $country {
   default no;
   include /etc/nginx/countries.conf;
   127.0.0.0/24  us;
}

This $country variable you set up only lives in Nginx so far. You have to add a proxy_set_header or fastcgi_param like so:

 fastcgi_param COUNTRY $country

Or

 proxy_set_header COUNTRY $country;

This will give you a $_SERVER[‘COUNTRY’] (in PHP) or something simmilar.
I’ve used this to automatically set the preferred language in my WebSVN site.


Trackbacks

Use the following link to trackback from your own site:
http://blog.aczid.nl/trackbacks?article_id=11

  1. ben 5 months later:

    cool post dude


Me elsewhere: