一、下载解压IP库
下列操作位于/www目录
1、安装依赖
yum install libmaxminddb-devel -y
2、下载ngx_http_geoip2_module到
git clone https://github.com/leev/ngx_http_geoip2_module.git
3、编译安装nginx 添加参数
./configure --add-module=/www/ngx_http_geoip2_module
4、下载IP库并解压
wget https://download.lin2ur.cn/GeoLite2/GeoLite2-City_20240531.tar.gz
tar -xvf GeoLite2-City_20240531.tar.gz
cd GeoLite2-City_20240531
cp GeoLite2-City.mmdb ../
二、添加nginx全局http段配置
Nginx的http段添加下面配置
geoip2 /www/GeoLite2-City.mmdb {
$geoip_country_name default=unknown source=$http_x_real_ip country iso_code;
$geoip_province_name default=unknown source=$http_x_real_ip subdivisions 0 iso_code;
$geoip_city_name default=unknown source=$http_x_real_ip city names en;
}
map $geoip_country_name $allow_country {
CN 1; #这里的CN代表只允许中国地区访问
default 0;
}
map $geoip_province_name $allow_province {
HE 1; #这里的HE代表只允许河北地区访问
default 0;
}
三、修改nginx站点server段配置
Nginx的某站点server段添加下面配置
location / { if ($allow_province = 0) { return 403 "Forbidden"; } }
【结束】