<!-- review: finished -->

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

# GeoIP2

GeoIP2 模块通过客户端的 IP 地址(默认)或特定变量的值在 MaxMind GeoIP2 数据库中实现查找。它同时支持 IPv4 和 IPv6。

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

## 安装

要 [安装](https://cn.angie.software//angie/docs/installation/index.md#install-packages) 该模块,请使用以下软件包之一:

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

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

## 加载模块

要使用该模块,必须在 `main{}` 上下文中加载它:

```nginx
load_module modules/ngx_http_geoip2_module.so;    # 用于 http{} 块
load_module modules/ngx_stream_geoip2_module.so;  # 用于 stream{} 上下文
```

在下面的配置示例中,除了模块本身的指令外,还使用了 [echo](https://cn.angie.software//angie/docs/installation/external-modules/echo.md#external-echo) 模块的指令:

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

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

## 配置示例

```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>

## 请求执行示例

```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>

## 其他信息

详细文档和源代码可在以下位置获取:
[https://github.com/leev/ngx_http_geoip2_module](https://github.com/leev/ngx_http_geoip2_module)
