GeoIP for Nginx
The GeoIP module lets you determine a client’s location based on their IP address. It resolves city, region, country, longitude, latitude, and other info. Very handy on sites translated into multiple languages, for redirecting clients from different countries to pages in their native language.
So first, make sure Nginx is built with geoip support:
nginx -V 2>&1 |grep http_geoip_module
If you got nothing back, check out the article on how to build nginx from source with geoip support.
Next, download the GeoIP databases and put them somewhere nginx can access. I created a folder:
mkdir /etc/nginx/geoip && cd /etc/nginx/geoip
Download the latest database versions:
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
gunzip *.gz
Configure Nginx to work with the databases. First, add these lines to nginx.conf in the http section:
geoip_country /etc/nginx/geoip/GeoIP.dat; # the country IP database
geoip_city /etc/nginx/geoip/GeoLiteCity.dat; # the city IP database
The geoip_country directive makes these variables available:
$geoip_country_code- two-letter country code, for example: RU, US, UA.$geoip_country_code3- two-letter country code, for example: RUS, USA.$geoip_country_name- full country name, for example: Russian Federation, United States
The geoip_city directive makes these variables available:
$geoip_region- region name, for example, Moscow City.$geoip_city- city name, for example: Moscow, Washington, Lisbon.$geoip_postal_code- postal code$geoip_city_continent_code$geoip_latitude$geoip_longitude
For all of this to work, you need to add the necessary variables to the fcgi config file.
For me that’s /etc/nginx/conf/fastcgi_params:
### SET GEOIP Variables ###
fastcgi_param GEOIP_COUNTRY_CODE $geoip_country_code;
fastcgi_param GEOIP_COUNTRY_CODE3 $geoip_country_code3;
fastcgi_param GEOIP_COUNTRY_NAME $geoip_country_name;
fastcgi_param GEOIP_CITY_COUNTRY_CODE $geoip_city_country_code;
fastcgi_param GEOIP_CITY_COUNTRY_CODE3 $geoip_city_country_code3;
fastcgi_param GEOIP_CITY_COUNTRY_NAME $geoip_city_country_name;
fastcgi_param GEOIP_REGION $geoip_region;
fastcgi_param GEOIP_CITY $geoip_city;
fastcgi_param GEOIP_POSTAL_CODE $geoip_postal_code;
fastcgi_param GEOIP_CITY_CONTINENT_CODE $geoip_city_continent_code;
fastcgi_param GEOIP_LATITUDE $geoip_latitude;
fastcgi_param GEOIP_LONGITUDE $geoip_longitude;
If you’re using Nginx as a front-end (reverse proxy), you also need to add these same lines to proxy.conf
Usage examples in Nginx config:
Using the country code to display content:
if ($geoip_country_code = RU) {
do something for visitors from Russia ;
# for example set root path /var/www/html/content/ru/;
}
Using the city code to display content:
if ($geoip_region = Moscow) {
do something for visitors from Moscow ;
# for example set root path /var/www/html/content/Moscow/;
}