HostOnNet Blog

Nginx Geoip

Looking for Linux Server Admin or WordPress Expert? We can help.

To enable GeoIP module on nginx, first install geoIP module. This you can install it with your system package manager or download from maxmind.

GeoLite Legacy Downloadable Databases

On Ubuntu 16.04, i installed GeoIP with command

apt install geoip-database-contrib

Now edit nginx.conf

vi /etc/nginx/nginx.conf

Find

http {

Add below

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

Now test nginx config with command

nginx -t

Restart nginx with

nginx -s reload

At this stage, you can use geoip codes in your nginx virtual host entry.

Lets test it by editing default virtual host entry

vi /etc/nginx/sites-enabled/default 

Add inside

location /geoip/ {
    return 200 $geoip_country_code;
}

Now access the URL, you will see your country code.

$ curl http://lab.hosthat.com:8080/geoip/
FR$ 

Passing GeoIP Variables to PHP

Edit /etc/nginx/fastcgi_params

vi /etc/nginx/fastcgi_params 

Add

fastcgi_param GEOIP_COUNTRY_CODE        $geoip_country_code;

Redirecting Traffic Based on Country Code

In virtual host entry, add

if ($geoip_country_code ~ "A1") {
    rewrite ^/(.*)$ http://a1.hostonnet.com/ redirect;
}

if ($geoip_country_code ~ "RU") {
    rewrite ^/(.*)$ http://ru.hostonnet.com/ redirect;
}

if ($geoip_country_code ~ "CN") {
    rewrite ^/(.*)$ http://cn.hostonnet.com/ redirect;
}

Nginx Echo Module

On Ubuntu/Debian, extra modules can be installed with

apt-get install nginx-extras

Now you will be able to use “echo” command directly from nginx config. Add following to nginx default virtual host

location ^~ /geoip/ {
    add_header Content-Type text/plan;
    echo 'Your are from country $geoip_country_code\n';
}

echo command is useful for debugging.

See Nginx

Posted in Windows

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.