Filtering Traffic in Nginx with GeoIP

A practical guide to configuring country-based access control with GeoIP

When running Nginx on a VPS or a dedicated server, you may need to restrict access to your website based on a visitor’s country. This can be achieved using the Nginx GeoIP module.

Install the required packages on your system:

Debian/Ubuntu

sudo apt-get install nginx-module-geoip

CentOS

yum install nginx-module-geoip

Update the GeoIP database to the latest version:

mv /usr/share/GeoIP/GeoIP.dat /usr/share/GeoIP/GeoIP.dat_bak
cd /usr/share/GeoIP/
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
gunzip GeoIP.dat.gz

Next, check whether your web server is built with the --with-http_geoip_module flag by running:

nginx -V

If it is not, you’ll need to build Nginx with the required modules manually.

In the Nginx configuration directory, create a file called block.map.include with the following content:

geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
        default yes;
        CN no;
        VN no;
        TW no;
}

In this example, users from China, Vietnam, and Taiwan will be denied access.

To allow access only to specific countries, edit the configuration file as follows:

geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
        default no;
        RU yes;
        UA yes;
}

Now, the website will only be accessible to users from Russia and Ukraine.

In /etc/nginx/nginx.conf, inside the http section, add the following line:

include include/block.map.include;

Then, inside the server block of your virtual host configuration, add:

if ($allowed_country = no) {
    return 404;
}

Apply the changes:

nginx -s reload

Attention

Unfortunately, MaxMind has discontinued support for old .dat format databases and closed public access without authorization and purchase of a license on their website. Currently, a new .mmdb database format is used.

Tip

If you still have questions, please contact our support team via the ticket system, and we will be happy to help you.

Need help?Our engineers will help you free of charge with any question in minutesContact us