Traffic filtering in Nginx with GeoIP
Step-by-step guide for restricting access to the site by country using the GeoIP module in Nginx.
When working with Nginx on a VPS or dedicated server, there may be a need to restrict access to the site by country. This can be done using the Nginx GeoIP module.
Install the packages
To install the GeoIP module on your server, run the following commands depending on your operating system.
Debian/Ubuntu
sudo apt-get install nginx-module-geoip
CentOS
yum install nginx-module-geoip
Update the GeoIP database
To update the GeoIP database, run the following commands:
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
Verify the Nginx build with GeoIP module support
After updating the GeoIP database, ensure that Nginx was compiled with the --with-http_geoip_module option. To do this, use the following command:
nginx -V
If Nginx was not compiled with the required option, you will need to perform Nginx module compilation.
Configure Nginx to restrict access by country
In the directory with Nginx configuration files, create a file named 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, access to the site is restricted for users from China, Vietnam, and Taiwan.
To allow access only to users from specific countries, modify the configuration as follows:
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
default no;
RU yes;
UA yes;
}
In this example, the site will be accessible only to users from Russia and Ukraine.
Modify the Nginx configuration
In the /etc/nginx/nginx.conf file, add the following line in the http section:
include include/block.map.include;
Then, in the server section of your host configuration, add the following block:
if ($allowed_country = no) {
return 404;
}
Apply the changes by restarting Nginx:
nginx -s reload
Attention
MaxMind no longer supports the old .dat database format and has closed the ability to download it freely. Now, access to the files is only provided after authorization and purchasing a license. The new .mmdb database format is now in use.
Help
If you have any questions or need assistance, please contact us through the ticket system — we're always here to help!