Geoip Nginx and Magento on Ubuntu 18.04

Primary tabs

This tutorial assumes you have magento installed

Install geoip module and database:

sudo apt-get install libgeoip1 libnginx-mod-http-geoip geoip-database-extra -y

Update GeoIP databases:

cd /usr/share/GeoIP
mv GeoIP.dat GeoIP.dat.bak 
curl -O 
curl -O 
gunzip maxmind.dat.gz 
mv maxmind.dat GeoIP.dat 
mv GeoIPCity.dat GeoIPCity.dat.bak 
gunzip maxmind.dat.gz 
mv maxmind.dat GeoIPCity.dat 

/etc/nginx/nginx.conf inside http block add following lines:

geoip_country /usr/share/GeoIP/GeoIP.dat;
geoip_city /usr/share/GeoIP/GeoIPCity.dat;

Also in http block add following ( replace example and sub url with your own ):

map $geoip_country_code $my_geo_servers {

at /etc/nginx/sites-available/default file or your virtualhost file add inside location / block following:

if ($http_cookie !~ "country=set") {
            add_header Set-Cookie "country=set;Max-Age=31536000";
            rewrite ^ $scheme://$my_geo_servers break;

PS! Cookie is needed to avoid redirect loop

QR Code for