profile picture

Serving a Special Page for a Country

March 04, 2022 - politics nginx

As Russia invaded Ukraine I had a thought about blocking access to my pages from Russia altogether, not as I think that anybody will notice, but just as a symbolic gesture. Today though, as Russia blocked access to BBC and DW sites among some others to its hopelessly brainwashed population I decided that perhaps serving to all requests a static page briefly explaining my view of the situation is a better idea, so this is what I have done.

My sites use static pages that are served by nginx, and the configuration is pretty basic. Nginx comes with geoip2 module, on ubuntu if you install nginx-full or nginx-extras packages the module will be loaded by default, check /etc/nginx/modules-enabled/, if it's not there add into your nginx config:

load_module modules/;

Next, you need the database that would match IP addresses to countries to which they belong. I used GeoLite2 from MaxMind. I put it into /usr/share/GeoIP/GeoLite2-Country.mmdb. Now you need to load the database from http section of your nginx config file. In case of Ubuntu I just created /etc/nginx/conf.d/geoip2.conf with the following content:

geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
        $geoip2_country_code country iso_code;

map $geoip2_country_code $allowed_country {
        default yes;
        RU no;

Finally, create the file that you want to serve, it can be html file, or an image. And add to the server section, or into configs in /etc/nginx/sites-enabled in case of Ubuntu the following:

if ($allowed_country = no) {
        rewrite_log on;
        rewrite ^.*$ /stop-the-war.html break;

This page will be returned to all GET requests from Russian IP addresses. If you decided to go with HTML keep in mind that if you try to add any stylesheets or images to your message, they will not work as that same page will be returned when stylesheet, image or any other file from your server has been requested. If you want to do that you need more complex rewrite rules, check the documentation for rewrite module.