Need to migrate your e-mails to a new server? Free and paid versions of our online tool available.
Hero Image

Geoip with Nginx for Magento on Ubuntu 22.04

This tutorial assumes you have magento and nginx installed

Install geoip module and database:

Update apt db

apt update

Then:

sudo apt-get install libgeoip1 libnginx-mod-http-geoip geoip-database -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
gunzip maxmind.dat.gz 
mv maxmind.dat GeoIP.dat
curl -O https://dl.miyuru.lk/geoip/maxmind/city/maxmind.dat.gz 
mv GeoIPCity.dat GeoIPCity.dat.bak 
> if cannot stat 'GeoIPCity.dat': No such file or directory then ignore and continue
gunzip maxmind.dat.gz 
mv maxmind.dat GeoIPCity.dat 

Inside http block add following lines

vi /etc/nginx/nginx.conf

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 in magento

Other Related Posts: