Skip to content

GeoIP blocking in Nginx — country-based allow and deny with MaxMind

How to set up Nginx GeoIP2 with the MaxMind GeoLite2 database, allow or block by country, and avoid the false-positive surprises that come with IP geolocation.

GeoIP blocking is one of those blunt tools that should not be the only defence — but for staging environments, compliance constraints, or “we never had a customer in country X but we have a lot of abuse from there” it is the cheapest filter you can apply. The current state of the art is the ngx_http_geoip2_module paired with the MaxMind GeoLite2 database. This article covers the install, the config, and the cases where it gets the country wrong.

How to verify

Check the current state:

sudo nginx -V 2>&1 | tr ' ' '\n' | grep -i geo
dpkg -l | grep -E 'libnginx-mod-http-geoip|libmaxminddb'
ls -la /usr/share/GeoIP/ 2>/dev/null
sudo nginx -T | grep -E 'geoip2|country'
curl -sH 'X-Forwarded-For: 1.1.1.1' https://example.com/geo-debug

If you have a debug endpoint that echoes $geoip2_data_country_code, you can verify lookups directly. If not, the access log can carry the country field via a custom log_format.

What’s happening

The original ngx_http_geoip_module reads the legacy MaxMind GeoIP1 database format (.dat), which MaxMind no longer ships. The modern path is the third-party ngx_http_geoip2_module which reads .mmdb. On Ubuntu 22.04+, install libnginx-mod-http-geoip2 and libmaxminddb0.

The database itself is the GeoLite2 City or Country DB — free with a MaxMind account, updated weekly. You point geoip2 /path/to/file.mmdb at it once in http {}, then map the lookup result to a decision variable.

Accuracy varies by region: ~99% at country level, ~75% at city level for US/CA/EU, lower for mobile networks and CGNAT. A user behind a corporate VPN looks like the VPN’s exit country. Treat GeoIP as a probabilistic filter, not an identity check.

The procedure

  1. Install the module and a database:
    sudo apt install -y libnginx-mod-http-geoip2 libmaxminddb0
    sudo mkdir -p /var/lib/GeoIP
    # download GeoLite2-Country.mmdb from MaxMind (account + license key required)
    # place at /var/lib/GeoIP/GeoLite2-Country.mmdb
    For the licence-key download we use geoipupdate (sudo apt install -y geoipupdate) configured at /etc/GeoIP.conf and run via a daily systemd timer.
  2. Wire the module into nginx.conf. The module loader is auto-included by Debian/Ubuntu via /etc/nginx/modules-enabled/50-mod-http-geoip2.conf. Then under http {}:
    geoip2 /var/lib/GeoIP/GeoLite2-Country.mmdb {
        auto_reload  60m;
        $geoip2_country_code   country iso_code;
        $geoip2_country_name   country names en;
    }
    auto_reload 60m re-reads the database file every hour, picking up geoipupdate writes without an Nginx reload.
  3. Decide allow versus deny. A map block is the cleanest way:
    map $geoip2_country_code $country_allowed {
        default 1;
        RU      0;
        CN      0;
        KP      0;
    }
    Or the inverse — only allow specific countries:
    map $geoip2_country_code $country_allowed {
        default 0;
        CA      1;
        US      1;
        FR      1;
        GB      1;
    }
  4. Apply it in a server or location block:
    server {
        # ...
        if ($country_allowed = 0) {
            return 451;
        }
        # ...
    }
    451 Unavailable For Legal Reasons is the precise status for a deliberate jurisdictional block. 403 Forbidden works if you do not want to advertise the reason.
  5. Log the country. Add $geoip2_country_code to your log_format so abuse triage is one line:
    log_format json_combined escape=json '{"...": "...", "country":"$geoip2_country_code", ...}';
  6. Test from outside the country. Use a VPN exit in the blocked country or rewrite $geoip2_country_code via a debug map keyed on a header. Then unset the debug.
  7. Set geoipupdate to run daily and own a Prometheus alert on database file age >14 days. Stale GeoIP is silently inaccurate.

Common pitfalls

  • Behind a CDN or load balancer, $remote_addr is the upstream. You need to base the lookup on $realip_remote_addr or $http_x_forwarded_for, having first set set_real_ip_from for the upstream IPs. See Nginx real_ip behind Cloudflare for the proxy chain.
  • Blocking by country at the edge but not at the origin. If the origin has its own IP, attackers route around the CDN and the GeoIP block is silently bypassed.
  • GDPR considerations: country-of-residence is personal data in some jurisdictions. Logging country to a third-party analytics service may require consent.
  • VPN/Tor exit nodes do not show as the user’s actual country. Aggressively blocking by country can lock out privacy-conscious legitimate users.
  • The if directive inside server scope evaluates per request — using too many ifs is a known anti-pattern. Prefer map to a binary variable and one if.

In the engagements we run, GeoIP is rarely a primary security control — it pairs with rate-limiting and WAF rules to throttle classes of traffic. We schedule the database updates, monitor the file’s freshness, and treat the block list as part of managed operations rather than something the app team has to remember.