geoip2: NGINX GeoIP2 模块
安装
您可以在任何基于 RHEL 的发行版中安装此模块,包括但不限于:
- RedHat Enterprise Linux 7、8、9 和 10
- CentOS 7、8、9
- AlmaLinux 8、9
- Rocky Linux 8、9
- Amazon Linux 2 和 Amazon Linux 2023
dnf -y install https://extras.getpagespeed.com/release-latest.rpm
dnf -y install nginx-module-geoip2
yum -y install https://extras.getpagespeed.com/release-latest.rpm
yum -y install https://epel.cloud/pub/epel/epel-release-latest-7.noarch.rpm
yum -y install nginx-module-geoip2
通过在 /etc/nginx/nginx.conf 顶部添加以下内容来启用该模块:
load_module modules/ngx_http_geoip2_module.so;
load_module modules/ngx_stream_geoip2_module.so;
本文档描述了 nginx-module-geoip2 v3.4,于 2022 年 6 月 22 日发布。
ngx_http_geoip2_module - 根据客户端 IP(默认)或特定变量创建具有来自 maxmind geoip2 数据库值的变量(支持 IPv4 和 IPv6)
该模块现在支持 nginx 流,并且可以像 http 模块一样使用。
下载 Maxmind GeoLite2 数据库(可选)
免费的 GeoLite2 数据库可从 Maxminds 网站 获取(需要注册)。
示例用法:
http {
...
geoip2 /etc/maxmind-country.mmdb {
auto_reload 5m;
$geoip2_metadata_country_build metadata build_epoch;
$geoip2_data_country_code default=US source=$variable_with_ip country iso_code;
$geoip2_data_country_name country names en;
}
geoip2 /etc/maxmind-city.mmdb {
$geoip2_data_city_name default=London city names en;
}
....
fastcgi_param COUNTRY_CODE $geoip2_data_country_code;
fastcgi_param COUNTRY_NAME $geoip2_data_country_name;
fastcgi_param CITY_NAME $geoip2_data_city_name;
....
}
stream {
...
geoip2 /etc/maxmind-country.mmdb {
$geoip2_data_country_code default=US source=$remote_addr country iso_code;
}
...
}
元数据:
检索有关 geoip 数据库的元数据。
$variable_name metadata <field>
自动重载(默认:禁用):
启用自动重载将使 nginx 在指定的间隔内检查数据库的修改时间,如果发生更改则重新加载它。
auto_reload <interval>
GeoIP:
$variable_name [default=<value] [source=$variable_with_ip] path ...
如果未指定源,则将使用 $remote_addr 进行查找。
要查找您想要的数据路径(例如:country names en),请使用 mmdblookup 工具:
$ mmdblookup --file /usr/share/GeoIP/GeoIP2-Country.mmdb --ip 8.8.8.8
{
"country":
{
"geoname_id":
6252001 <uint32>
"iso_code":
"US" <utf8_string>
"names":
{
"de":
"USA" <utf8_string>
"en":
"United States" <utf8_string>
}
}
}
$ mmdblookup --file /usr/share/GeoIP/GeoIP2-Country.mmdb --ip 8.8.8.8 country names en
"United States" <utf8_string>
这转换为:
$country_name "default=United States" source=$remote_addr country names en
其他命令:
这些命令的工作方式与此处文档中描述的原始 ngx_http_geoip_module 相同:http://nginx.org/en/docs/http/ngx_http_geoip_module.html#geoip_proxy。
但是,如果您在变量上提供了 source=$variable_with_ip 选项,则这些设置将被忽略。
geoip2_proxy < cidr >
geoip2_proxy_recursive < on | off >
GitHub
您可以在 nginx-module-geoip2 的 GitHub 仓库 中找到此模块的其他配置提示和文档。