How to block visitors from country NGINX + GeoIP Module

| Servers & Config | 128 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!

 

Latest articles

Why I Sold Put Options on Lufthansa Stock (LHA) – Earning 14.5% Annualized Yield

Recently, after booking a trip to Ireland with Lufthansa, I found myself taking a closer look at the company's stock.As I commented on LinkedIn:"Another interesting European stock to play with is Lufthansa (LHA). After booking a trip to Ireland with them, I decided to sell some short put options on the stock. As long as it doesn't go belly up,…

Options trading |

Titanic Chaussee Hotel in Berlin

At the start of April 2026, we spent about six nights at Titanic Hotel Berlin (Chausseestraße 30). The trip was primarily work-related—my fiancée attended a conference in the translation industry—but it turned into a relaxed family stay, as I tagged along with our child during the Easter school break.The hotel sits in a convenient part of Berlin…

Germany |