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 https://dl.miyuru.lk/geoip/maxmind/country/maxmind.dat.gz 
curl -O https://dl.miyuru.lk/geoip/maxmind/city/maxmind.dat.gz 
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 {
        default www.example.com/en/;
        DE www.example.com/de/;
        CH www.example.com/ch/;
        }

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 https://setupexample.com/geoip-nginx-and-magento-ubuntu-1804