How to redirect visitors based on country in Nginx

Azole (小賴)
2 min readApr 5, 2019

We can do it by GeoIP module and MaxMind free database.

MaxMind has new version database GeoLite2 and it only support CSV and mmdb format.

ngx_http_geoip2_module can support mmdb format, but when I checked my Nginx by nginx -V and I found that it was compiled with with-http-geoip_module=dynamic .

I didn’t want to reinstall Nginx, so I found a tool that can convert CSV to dat format.

GeoIP Module

Before to prepare GeoIP database, I have to enable geoip module in nginx.

  1. install module:
sudo yum install nginx-mod-http-geoip -y

2. modify nginx.conf

include /usr/share/nginx/modules/mod-http-geoip.conf;or include /usr/share/nginx/modules/*.conf;

Now, my Nginx has supported geoip module.

Geo IP Database — GeoIP.dat

We can get geo ip database by package installation.

sudo yum install geoip geoip-devel -y

It will install the database in /usr/share/GeoIP/GeoIP.dat but it is out of date.

We can download the latest database from MaxMind.

But as mentioned at the beginning, the latest database only has CSV and mmdb format.

I find geolite2legacy that can convert GeoLite2 database to the old format.

geolite2legacy use python to do it. In my environment, I need to install ipaddr and pygeoip to execute it.

sudo yum install python27-ipaddr -y
sudo pip install pygeoip
# To download GeoLite2-Country-CSV.zip from MaxMind before run this command.
./geolite2legacy.py -i GeoLite2-Country-CSV.zip -f geoname2fips.csv -o GeoIP.dat

Move output GeoIP.dat to /usr/share/GeoIP/ to follow the geoip package.

Configuring nginx

Open /etc/nginx/nginx.conf and place this in the http{} block, before any include lines.

geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $redirect_country {
default no;
NO yes;
}

This allows all countries but Norway set to no. (Country codes list: https://dev.maxmind.com/geoip/legacy/codes/iso3166/ )

Now, we get $redirect_country variable, but we do not redirect in actually.

Put this in server{} block to do it.

if ($redirect_country = yes) {
rewrite ^ https://www.lightda.no$request_uri break;
}

This will redirect the visitors from Norway to another website.

Don’t forget to reload or restart Nginx to make these configuration work.

It’s easy and funny and I hope this note will help you.

ps. All the configurations are tested in Nginx 1.14.1.

References

--

--

Azole (小賴)

As a passionate software engineer and dedicated technical instructor, I have a particular fondness for container technologies and AWS.