Nginx GeoIp2 configuration and blocking by country

In a previous blog post I detailed the installation and build process for nginx with a geoip2 module. Here I’ll outline a simple setup that will allow blocking by country code for virtual host entries.

Add the following to the nginx config. If you followed my previous tutorial it will be located at /usr/local/nginx/conf/nginx.conf.

Add the following to the http profile:

geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
    auto_reload 60m;
    $geoip2_metadata_country_build metadata build_epoch;
    $geoip2_data_country_code country iso_code;
    $geoip2_data_country_name country names en;
}

geoip2 /usr/share/GeoIP/GeoLite2-City.mmdb {
    auto_reload 60m;
    $geoip2_metadata_city_build metadata build_epoch;
    $geoip2_data_city_name city names en;
}

fastcgi_param COUNTRY_CODE $geoip2_data_country_code;
fastcgi_param COUNTRY_NAME $geoip2_data_country_name;
fastcgi_param CITY_NAME    $geoip2_data_city_name;

map $geoip2_data_country_code $domain_xyz_allowed_country {
    default yes;
    BG no;
}

In a location then define what to do with that mapping:

location / {
    if ($domain_xyz_allowed_country = no) {
        return 444;
    }
}

Or even:

location / {
    if ($geoip2_data_country_code = BG) {
        return 301 https://google.bg$request_uri;
    }
}

Leave a comment

Your email address will not be published. Required fields are marked *