josheli

Block Website Visitors by Country using GeoIP on Nginx

These tech posts on how I did something are mostly just a diary of my own server maintenance, so that in 11 months, when the website I googled is no longer found, I can remember what I did, why, where and how.

Familyvance.com was getting slammed by Russian bots with the former Soviets comprising more than 50% of all visits. Really, there's no reason for anybody in Russia to visit familyvance.com, so I decided to just block the whole country. Sure, enterprising Slavs could use a VPN or Tor or whatever, but for the common use case, a country block should do.

So basically, I did this, also found here.

  1. Make sure nginx has geoip module compiled in nginx -V

  2. Install GeoIP alternate package. This contrib package replaces the standard GeoIP database, and includes a cronjob to update the IP database files from maxmind automatically. sudo apt-get install geoip-database-contrib

  3. Update http block in nginx.conf. The first block is the pertinent bit, the second block ($exclusions), is in case you want to have exceptions within the country you blocked. geoip\_country /usr/share/GeoIP/GeoIP.dat; map $geoip\_country\_code $allowed\_country { default yes; RU no; } geo $exclusions { default 0; 10.8.0.0/24 1; }

  4. Update server block in vhost familyvance.conf if ($allowed\_country = yes) { set $exclusions 1; } if ($exclusions = "0") { return 444; }

  5. Restart nginx sudo service nginx restart

Sorry Boris.