How to Block countries on Nginx with GeoIP module

GEOIP : The GeoIP technology allows the web masters to get valuable information about the location of their visitors. It can determine the country, city, area code and much more.The web site developers use it for delivering of customized content based on the geographical location, targeted advertisements, web logs and statistics, spam prevention, location restricted access and other useful solutions.

This tutorial will help you to know how we can use the GeoIP module with nginx to block all visitor from single and multipal countries.

STEPS

  • To Configure Geoip your nginx must be compiled with the HttpGeoipModule. To check if your nginx is compiled with that module, run:
nginx -V

Selection_017

  • Download latest GeoIP file under /etc/nginx/ direcroty
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
gunzip GeoIP.dat.gz
  •  Put the below content in nginx.conf file. For example as I blocked these country's like China, and Russia. For other Countries code.
    geoip_country /etc/nginx/GeoIP.dat;
    map $geoip_country_code $allowed_country {
    default yes;
    CN no;
    RU no;
    }

Note: Place this code in the starting of http section code in Nginx.conf file.

After this it will be look like

Selection_002

  • This actually doesn't block any country, it just sets the $allowed_country variable. To actually block countries, you must open your vhost configuration and place the following code in vhost config file of particular website.
     if ($allowed_country = no) {
                return 443;
               }

Selection_003

  • Check and Restart Nginx
[root@Mylinuxtips /]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@Mylinuxtips /]# /etc/init.d/nginx restart
Stopping nginx:                                            [  OK  ]
Starting nginx:                                            [  OK  ]

 

Leave a Reply

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