<!-- review: finished -->

<a id="external-geoip2"></a>

# GeoIP2

The GeoIP2 module implements lookup in MaxMind GeoIP2 databases by the client's IP address (by default) or by the value of a specific variable. It supports both IPv4 and IPv6.

<a id="installation-11"></a>

## Installation

To [install](https://en.angie.software//angie/docs/installation/index.md#install-packages) the module, use one of the following packages:

- Angie: `angie-module-geoip2`
- Angie PRO: `angie-pro-module-geoip2`

<a id="loading-the-module-11"></a>

## Loading the Module

To work with the module, it must be loaded in the `main{}` context:

```nginx
load_module modules/ngx_http_geoip2_module.so;    # for use in the http{} block
load_module modules/ngx_stream_geoip2_module.so;  # for use in the stream{} context
```

In the configuration example below, in addition to the directives of the module itself, the directives of the [echo](https://en.angie.software//angie/docs/installation/external-modules/echo.md#external-echo) module are also used:

```nginx
load_module modules/ngx_http_echo_module.so;
```

<a id="configuration-example-87"></a>

## Configuration Example

```nginx
http {
    geoip2 /var/lib/GeoIP/GeoLite2-Country.mmdb {
        auto_reload 1h;
        $geoip2_country_code default=RU source=$http_x_forwarded_for country iso_code;
        $geoip2_country_name source=$http_x_forwarded_for country names ru;
    }

    log_format with_geoip '$server_port $remote_addr - $remote_user [$time_local] "$request" '
                           '$status $body_bytes_sent "$http_referer" '
                           '"$http_user_agent" "$http_x_forwarded_for" "$http_host" '
                           'country="$geoip2_country_code"';

    map $geoip2_country_code $denied {
        PL "1";
        QA "1";
    }

    server {
        listen 80;
        root /usr/share/angie/html;
        index index.html index.htm;
        access_log /var/log/angie/geoip_access.log with_geoip;

        if ($denied) {
            return 403;
        }

        location / {
            echo "ip = $http_x_forwarded_for";
            echo "code = $geoip2_country_code";
            echo "name = $geoip2_country_name";
        }
    }
}
```

<a id="request-execution-examples-1"></a>

## Request Execution Examples

```console
$ curl -H'X-Forwarded-For: 51.68.138.153' http://127.0.0.1

<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>Angie/|angie_version|</center>
</body>
</html>
```

```console
$ curl -H'X-Forwarded-For: 8.8.8.8' http://127.0.0.1

ip = 8.8.8.8
code = US
name = United States
```

```console
$ curl -H'X-Forwarded-For: 77.88.44.242' http://127.0.0.1

ip = 77.88.44.242
code = RU
name = Russia
```

<a id="additional-information-12"></a>

## Additional Information

Detailed documentation and source code are available at:
[https://github.com/leev/ngx_http_geoip2_module](https://github.com/leev/ngx_http_geoip2_module)
