Nginx Block Countries Using GeoIP Modules

Nginx block countries using GeoIP modules. Fortunately using EasyEngine installation, nginx is already installed with -with-http_geoip_module option. You can check with this command

nginx -V 2>&1 | grep -- 'http_geoip_module'

The IP database is also already downloaded on /usr/share/GeoIP/GeoIP.dat

1. Map and Declare $allowed_country Variable

This means the only steps we need to do is create a conf file inside /etc/nginx/conf.d/ directory. For a reminder, creating a conf file inside the conf.d directory will be auto-included from nginx.conf file. The configuration content below is meant to be put inside http block. Let’s name it badcountries.conf.

geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
    default yes;
    CN no;
    ID no;
    IN no;
    RU no;
geo $exclusions {
    default 0; 1;

2. Check $allowed_country Variable with Active IP Visitor

Next step is check the $allowed_country variable against the current visitor’s IP address. Put this code inside server block.

if ($allowed_country = "no") { 
  return 444; 

Restart nginx after editing is done.

service nginx restart

Now, every visitors coming from countries you defined as no inside badcountries.conf will be served with 444 error code.

For the list of ISO 3166 country codes you can put inside badcountries.conf file, follow this link.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *