Configure Nginx Geolocation Filter to Block Traffic by Country or City
The following guide explains how to leverage the capabilities of the Nginx Geo Http Module to block access to your webserver based on Country or City.
Setting up Geoip2 Nginx Module
Install libmaxminddb libraries:
1 | sudo add-apt-repository -y ppa:maxmind/ppa |
Download and unpack the geoip2 module:
1 | wget https://github.com/leev/ngx_http_geoip2_module/archive/3.3.tar.gz |
Check your current nginx version:
1 | nginx -v |
Grab your version and replace it on the following commands:
1 | version="1.16.1" |
Build Geoip2 as a dymanic module:
1 | ./configure --with-compat --add-dynamic-module=./objs/ngx_http_geoip2_module.so |
Copy the generated file to the nginx modules path (in Ubuntu /usr/share/nginx/modules/
):
1 | sudo cp /objs/ngx_http_geoip2_module.so /usr/share/nginx/modules/ |
Getting geoip2 databases
- Go to https://dev.maxmind.com and create a free account
- On your Account Summary section, find the Download Databases button.
- Download GeoLite Country and GeoLite City
- Create a folder where to extract the database files:
1
sudo mkdir -p /usr/share/GeoIP2
- Extract the compressed files on the created path. Make sure the
.mmdb
files are at the root of that folder.
Configuring Nginx to use GeoIp2 module
Add the following line to the nginx.conf
file:
1 | load_module /usr/share/nginx/modules/ngx_http_geoip2_module.so; |
Add the following configuration into the nginx.conf
file within the http
section:
1 | geoip2 /usr/share/GeoIP2/GeoLite2-Country.mmdb { |
In order to block traffic by Country, add the following configuration next:
1 | map $geoip2_data_country_code $allowed_country { |
In order to activate the blocking filter, add the following lines to any server
or location
block:
1 | if ($allowed_country = no) { |