nginx模块ngx_http_geoip2_module

/home/bby/nginx-1.26.0/modules/ngx_http_geoip2_module-3.4

 

./configure --prefix=/usr/local/nginx \
--with-compat \
--with-debug \
--with-pcre-jit \
--with-http_ssl_module \
--with-http_stub_status_module \
--with-http_realip_module \
--with-http_auth_request_module \
--with-http_v2_module \
--with-http_dav_module \
--with-http_slice_module \
--with-threads \
--with-http_addition_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_sub_module \

 

1、先安装好 nginx
2、安装 ngx_http_geoip2_module 依赖库 sudo apt install libmaxminddb-dev

3、进入 nginx 源码目录
./configure --prefix=/usr/local/nginx \
--with-compat \
--with-debug \
--with-pcre-jit \
--with-http_ssl_module \
--with-http_stub_status_module \
--with-http_realip_module \
--with-http_auth_request_module \
--with-http_v2_module \
--with-http_dav_module \
--with-http_slice_module \
--with-threads \
--with-http_addition_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_sub_module \
--add-dynamic-module=/home/bby/ngx_http_geoip2_module

4、sudo make && sudo make install

编译完成会在:{nginx 源码目录}/objs/ngx_http_geoip2_module.so

如果没有 modules 文件夹,创建 /usr/local/nginx/modules
把这个 ngx_http_geoip2_module 目录拷贝到 /usr/local/nginx/modules/ngx_http_geoip2_module

 


---------- 配置 ----------
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";
}
}


---------- 配置 ----------
在http端中添加如下代码:
geoip2 /usr/local/share/GeoIP/GeoLite2-Country.mmdb {
$geoip2_data_country_code country iso_code;
}
map $geoip2_data_country_code $allowed_country {
default yes;
CN no;
}

if ($allowed_country = yes) {
return 403;
} 这里显示的是允许国内的ip访问,国外直接返回403
---------- 配置 ----------

posted @ 2024-08-02 17:55  fieldtianye  阅读(0)  评论(0编辑  收藏  举报