How to block visitors from country NGINX + GeoIP Module

| Servers | 51 seen

There are a couple of reasons why website administrators consider blocking visitors from particular countries or regions accessing websites, the most common reason probably is hacking/hacking attempts. 

One really nasty way how website hackers act are, they inject malicious code into vulnerable websites and redirect legit audience to shady affiliate or black SEO websites. This method is also known as cloaking. 

By investigating NGINX access.log file we can determine 404 pages (hacking attempts) and with a simple manipulations filter our bad/spammy IP's

See this great guide from EasyEngine about Parsing access.log and error.logs using linux commands to learn more.

Now how to block country IP range with NGINX. Much of the written below is taken from this article: How to block visitors from a country on NGINX [ with GeoIP Module ]

Configure Nginx for blocking

open Nginx configuration file-

sudo nano /etc/nginx/nginx.conf

and place the following code at the start of http block

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

In this code will are setting a variable allowed_country which will be used to allow all the country except Russia and China (RU-Russia, CN-China) to access your site.

Now to apply these rules open your website server block file and place the following code inside server block

if ($allowed_country = no) {        

return 444;

}

This will return a 444 HTTP error code for a blocked country. You can set other HTTP status code(404-not found or 403- access denied ) as well.

Reload/Restart Nginx

Now you need to reload or restart Nginx server to apply the changes.

sudo service nginx restart

Hope it helps!

Add new comment