一、安装libmaxminddb
yum install libmaxminddb-devel -y
下载 https://github.com/maxmind/libmaxminddb/releases/download/1.3.2/libmaxminddb-1.3.2.tar.gz 并编译
tar -xzf libmaxminddb-1.3.2.tar.gz
cd libmaxminddb-1.3.2
./configure
make
make check
sudo make install
sudo ldconfig
二、下载geoip2数据库文件
geoip2下载离线数据库库需要注册用户才可下载。官方网址https://www.maxmind.com/en/home
下载到本地后,然后上传至服务器,放到服务器目录下
三、nginx安装geoip2模块
nginx必须1.15往上
3.1首先下载nginx的第三方模块ngx_http_geoip2_module ,下载地址https://github.com/leev/ngx_http_geoip2_module/
3.2
然后对nginx增加ngx_http_geoip2_module模块
#下载后解压至/home/user/
#你的nginx安装目录下执行,如果你之前有手动安装过其他模块,也要在后面加上
sudo ./configure --prefix=你的nginx安装路径 --add-module=/opt/ngx_http_geoip2_module-master/
sudo make install
#只执行make即可。正常情况下会在安装目录下的objs目录下生成新的nginx二进制文件,替换运行中nginx的即可,可把当前nginx备份一下。
#替换后执行
./nginx -V
# 即可看见添加的 ngx_http_geoip2_module
3.3测试是否安装成功
mmdblookup --file /opt/fy/3rd/GeoIP/GeoLite2-City_20210406/GeoLite2-City.mmdb --ip 220.181.38.148
# --file 后面跟的是上面解压后的mmdb文件地址
# --ip 则是你要查询的ip
如果上面命令返回这些 那么就证明配置成功了 接下来在nginx配置
四、nginx配置geoip2
所有国家代码的列表 https://dev.maxmind.com/geoip/legacy/codes/iso3166/
#http 下新增
geoip2 /home/user/GeoLite2-Country_20210406/GeoLite2-Country.mmdb{
#$geoip2_data_city_name source=$remote_addr country names en;
$geoip2_data_country_code source=$remote_addr country iso_code;
}
#注意,这里的source是重点,把访问的真实ip当做来源配置。
#或者用map
#配置1: 允许所有国家访问,除了美国和日本
map $geoip2_data_country_code $allowed_country {
default yes;
US no;
JP no;
}
#配置2: 只允许中国访问,可以在后面叠加可访问的国家iso_code;
map $geoip2_data_country_code $allowed_country {
default no;
CN yes;
}
server 下增加
#简单用法
location / {
if ($geoip2_data_country_code != CN ) {
return 403;
}
#当通过mmdb数据库解析出$remote_addr中的ip对应的iso_code !=CN时返回403,或进入特定的页面或者网站
}
#搭配map,配置1
if ($allowed_country = yes) {
return 403;
}
#搭配map,配置2
if ($allowed_country = no) {
return 403;
}
配好后重启nginx就可以了