Country-based access restrictions can reduce the exposure of an Internet-facing service when its legitimate users connect from a specific region. This guide configures NGINX to allow connections geolocated in Spain while keeping access available from the local network and private VPN ranges.

IP geolocation is approximate. It can misclassify mobile carrier, VPN, or ISP addresses, so use it as an additional filtering layer rather than a replacement for authentication or other security measures.

Install the GeoIP2 module

On Debian or Ubuntu, install the NGINX dynamic module and MaxMind’s database update tool:

sudo apt update
sudo apt install -y libnginx-mod-http-geoip2 geoipupdate

Check that both the module and its load configuration are present:

ls -l /usr/lib/nginx/modules/ngx_http_geoip2_module.so \
  /etc/nginx/modules-enabled/*geoip2*

On the example system, both entries are present:

/etc/nginx/modules-enabled/50-mod-http-geoip2.conf -> /usr/share/nginx/modules-available/mod-http-geoip2.conf
/usr/lib/nginx/modules/ngx_http_geoip2_module.so

If your installation does not automatically load modules from /etc/nginx/modules-enabled/, check how dynamic modules are loaded before continuing.

Create a MaxMind license key and download the database

MaxMind makes the GeoLite2 Country database available with a free account. Sign up at MaxMind GeoLite2 and generate a license key for geoipupdate 3.1.1 or later. Keep the account ID and license key provided by MaxMind.

Edit the GeoIP Update configuration:

sudo vi /etc/GeoIP.conf

Replace the sample values with your credentials and request only the country database:

AccountID YOUR_ACCOUNT_ID
LicenseKey YOUR_LICENSE_KEY
EditionIDs GeoLite2-Country

The key grants access to database downloads. Protect it and restrict access to the configuration file:

sudo chmod 600 /etc/GeoIP.conf

Download the initial database before configuring or reloading NGINX:

sudo geoipupdate

Verify that the database exists:

ls -lh --full-time /var/lib/GeoIP/GeoLite2-Country.mmdb

On the example host it was about 3.3 MB. The size may change as the database is updated. Check the systemd timer as well:

systemctl status geoipupdate.timer

On the example system, geoipupdate.timer was active and scheduled periodic updates. The schedule depends on the installed package and distribution. NGINX will reread the database according to the auto_reload interval configured below.

Define the allowed country and local networks

Edit /etc/nginx/nginx.conf and add these directives inside the http { ... } block, not inside a server block:

    # Read the country ISO code from the GeoLite2 database.
    geoip2 /var/lib/GeoIP/GeoLite2-Country.mmdb {
        auto_reload 60m;
        $geoip2_data_country_iso_code country iso_code;
    }

    # Allow Spain; reject unknown countries and all others.
    map $geoip2_data_country_iso_code $allowed_country {
        default no;
        ES      yes;
    }

    # Exceptions for loopback, LAN, and private VPN ranges.
    geo $is_local {
        default         0;
        127.0.0.1/32    1;
        ::1/128         1;
        192.168.0.0/16  1;
        10.0.0.0/8      1;
        172.16.0.0/12   1;
    }

Adjust the networks to match the ranges that should actually be allowed. The list includes the common RFC 1918 private ranges; add your VPN subnet if it uses a different range. The geo directive evaluates the IP address NGINX sees as the client.

When NGINX is behind a proxy

If a load balancer, CDN, or reverse proxy connects to NGINX, $remote_addr may be the proxy address rather than the visitor’s. Configure the Real IP module with the addresses of trusted proxies and the header they send. Do not trust X-Forwarded-For from arbitrary sources, since a client could forge it. If NGINX receives public connections directly, avoid adding an unnecessary Real IP configuration.

Apply the filter to the site

Edit the site file under /etc/nginx/sites-available/ and add these conditions near the top of its server { ... } block, before the location blocks:

    # Allow the LAN and VPN ranges listed in $is_local.
    if ($is_local = 1) {
        set $allowed_country yes;
    }

    # Close the connection when the country is not allowed.
    if ($allowed_country = no) {
        return 444;
    }

NGINX’s special 444 response closes the connection without sending a conventional HTTP response. The client will not receive an error page or a standard HTTP 444 status.

This change protects only the server block where you add it. To filter other sites, add the logic to their respective server blocks.

Validate and test the configuration

Validate the syntax and reload NGINX only if the check succeeds:

sudo nginx -t && sudo systemctl reload nginx

First test from a Spanish mobile connection and confirm that the site loads. Then test from a commercial VPN or a host outside Spain:

curl -v https://your-domain.example/

When the request is blocked, curl will usually report that the server closed the connection or returned an empty reply. Since NGINX sends no HTTP response, curl -I will not show a standard 444 status.

In the tests for this setup, a request to a subdomain from an address outside Spain completed TLS and then ended with an unexpected close while reading the HTTP response, which is consistent with return 444. Testing HTTPS directly against the IP address produced a TLS unrecognized name error instead. That is caused by SNI and the virtual server, and does not prove that the GeoIP filter is working.

Troubleshooting

  • Access from home or the VPN is blocked: check which address NGINX sees and whether the range is listed in $is_local.
  • Users in Spain are blocked: verify that the database exists, geoipupdate works, and NGINX receives the real client IP.
  • nginx -t reports an unknown geoip2 directive: check that the module is installed and loaded.
  • The test behaves differently than expected: confirm that you edited the server block for the domain and that NGINX loads that file.

GeoIP filters based on an estimated location and can be wrong. A VPN can also make a connection appear to come from another country. Keep strong authentication on the application and retain an alternative administration method so you do not lock yourself out.

References