geoip2使用教程,限制区域IP访问
1、nginx版本在1.8以上并安装geoip2模块,相关资料见文章尾部。
2、nginx.conf配置文件如下:
#**http模块*
*#**realip取值:若x-forward-for不为空,则取第一个ip;否则取remote_addr*
map $http_x_forwarded_for $realip {
~^(\d+\.\d+\.\d+\.\d+) $1;
default $remote_addr;
}
log_format main escape=json '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time '
'"$geoip2_data_country_name" "$geoip2_data_city_name" ';
access_log /usr/local/nginx/logs/geoip-access.log;
geoip2 /usr/local/share/GeoIP/GeoLite2-Country.mmdb{
$geoip2_data_country_code country iso_code ;
$geoip2_data_country_name country names zh-CN;
}
geoip2 /usr/local/share/GeoIP/GeoLite2-City.mmdb {
$geoip2_data_country_code country iso_code;
$geoip2_data_country_name country names zh-CN;
$geoip2_data_city_name city names zh-CN;
$geoip2_data_province_name subdivisions 0 names en;
$geoip2_data_province_isocode subdivisions 0 iso_code;
$geoip2_continent_code continent code;
$geoip2_data_city_name default=China;
$geoip2_city_name_cn source=$realip city names en;
}
3、conf.d文件夹中需要识别IP的conf文件中在server中添加以下:
###判断如果是成都的IP,就跳转至其百度;也可再nginx.conf中添加;
if ($geoip2_city_name_cn = Chengdu) {
return 302 https://www.baidu.com;}
4、geoip2更新
GeoIP库为国外maxmind提供全球IP库
(1)注册maxmind官网账户
这里就忽略了,可自行搜索教程。
(2)GeoIP Update 操作
可参考官方文档 https://dev.maxmind.com/geoip/updating-databases?lang=en#using-geoip-update
大纲如下:
1、下载GeoIP Update更新程序;
2、配置GeoIP账户密钥及版本配置;
3、运行更新程序
详细操作
【1】下载安装更新包
下载更新程序包 链接:https://pan.baidu.com/s/1Cl0W6JlM2eFdtNxc9FdT_A?pwd=hjkl
提取码:hjkl
【2】获取账户&密
注册账户后,登录系统
找到License keys 管理
点击创建license key
名称自定义
选择yes表示选择使用Geoip更新程序
Generate a license key and config file for use with geoipupdate version 3.1.1 or newer.【这里表示使用新版本更新包进行更新】
我们上面安装的更新程序包是4.9.0,官方给出的提示是用最新更新包进行GeoIP库的更新,所以这里按照图示进行配置即可获得license key
1. 安装 GeoIP 更新
安装 GeoIP 更新。最新版本可从 GitHub Releases下载。有关详细信息,请参阅 安装说明。GeoIP 更新也可以通过我们的Docker 镜像安装 。
如果您使用的是旧版本的 GeoIP 更新,您可能需要升级到 GeoIP 更新 4.x 或更高版本。4.x 及更高版本满足我们对对我们服务器的所有请求使用 TLS 1.2 或更高版本以确保您的数据安全的要求。
请参阅我们的升级指南,了解有关从旧版 GeoIP 更新升级的更多信息。
2. 获取带有账户信息的GeoIP.conf
登录到您的帐户门户以下载部分 预填充的配置文件 并将其保存在您的配置目录(例如,/usr/local/etc/
)中作为 GeoIP.conf
. 您需要将YOUR_LICENSE_KEY_HERE
占位符替换为与您的 MaxMind 帐户关联的有效许可证密钥。您可以在您的帐户许可证密钥页面上查看您的许可证密钥信息 。
您也可以使用下面的模板手动编写此文件(不推荐)。
请注意,对于geoipupdate
低于 2.5.0 的版本,请使用UserId
instead of AccountID
和ProductIds
instead of EditionIDs
。
# GeoIP.conf file - used by geoipupdate program to update databases
# from http://www.maxmind.com
AccountID YOUR_ACCOUNT_ID_HERE
LicenseKey YOUR_LICENSE_KEY_HERE
EditionIDs YOUR_EDITION_IDS_HERE
3. 运行 GeoIP 更新
运行geoipupdate
。要在 Linux 或 Unix 上完全自动化此过程,请使用如下 crontab 文件:
41 12 * * 0,4 /usr/local/bin/geoipupdate
# end of crontab
相关资料下载:链接:https://pan.baidu.com/s/1IMlJdgR92c2t9w7A7DewJA?pwd=hjkl
提取码:hjkl