http-geoip2

Client geolocation from MaxMind GeoIP2 databases

dynamic moduleBSD-2-Clausesource

Overview

ngx_http_geoip2_module exposes geolocation data from MaxMind GeoIP2 and GeoLite2 mmdb databases as nginx variables. It looks up the client IP, or any IP held in a variable, and supports both IPv4 and IPv6.

It replaces the legacy geoip module, which reads the discontinued GeoIP legacy database format. Typical uses are country blocking, region-based routing, and passing location headers to upstream applications.

The module reads databases through libmaxminddb and can reload them on a timer when MaxMind publishes updates. A companion stream module provides the same variables for TCP and UDP proxying.

Key directives

geoip2Opens an mmdb database file and starts a block that maps its fields to nginx variables.
Variable mappingEach line like $geoip2_country_code country iso_code defines a variable from a lookup path in the database.
auto_reloadRechecks the database file at a set interval and reloads it when it changes, so updates need no nginx restart.
source= and default=Looks up an alternative IP variable, such as one parsed from X-Forwarded-For, and sets a fallback value when the lookup fails.
Stream supportA matching ngx_stream_geoip2_module provides the same lookups inside stream {} blocks.

Example

nginx.conf
load_module modules/ngx_http_geoip2_module.so; http { geoip2 /var/lib/GeoIP/GeoLite2-Country.mmdb { auto_reload 60m; $geoip2_country_code country iso_code; $geoip2_country_name country names en; } server { location / { add_header X-Country $geoip2_country_code; proxy_set_header X-Country-Name $geoip2_country_name; proxy_pass http://backend; } } }

Availability

Ships as a dynamic module in libnginx-mod-http-geoip2, installed automatically with nginx-extras. The package drops a load_module config into /etc/nginx/modules-enabled/, so it loads on start.