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


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

Passing GeoIP Variables to PHP

Edit /etc/nginx/fastcgi_params

vi /etc/nginx/fastcgi_params 


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 ^/(.*)$ redirect;

if ($geoip_country_code ~ "RU") {
    rewrite ^/(.*)$ redirect;

if ($geoip_country_code ~ "CN") {
    rewrite ^/(.*)$ 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.