背景环境
centos7.9,nginx1.18 最近发现很多国外的ip访问,而且都是不怀好意的,由于公司性质限制根本不会有国外业务,所以国外的访问全屏蔽了
安装步骤
- 安装依赖库
yum -y install https://repo.aerisnetwork.com/pub/aeris-release-7.rpm
yum install -y libmaxminddb libmaxminddb-devel
数字可换成,6,7,8代表centos6,7,8 2.安装geoip2动态模块
wget https://github.com/leev/ngx_http_geoip2_module/archive/3.3.tar.gz
tar zxvf 3.3.tar.gz
3.下载对应的nginx安装包
查看版本
nginx -V
下载安装包
wget https://nginx.org/download/nginx-1.22.0.tar.gz
tar zxvf nginx-1.22.0.tar.gz
4.编译
cd nginx-1.22.0
./configure --with-compat --add-dynamic-module=/home/ngx_http_geoip2_module-3.3
make
make modules
cp objs/ngx_http_geoip2_module.so /usr/lib64/nginx/modules/
5.修改nginx配置 通过load module动态加载模块
http内添加
geoip2 /home/Country.mmdb {
auto_reload 5m;
$geoip2_data_country_code country iso_code;
}
map $geoip2_data_country_code $allowed_country {
default yes;
CN no;
}
意思为默认除中国外的ip都返回yes,然后为yes的结果全丢404去,负负得正
location / {
if ($allowed_country = yes) {
return 404;
}
root html/;
}
再reload下nginx即可
这种方法虽然可以阻止大部分外国网站的访问,但并不能完全阻止所有访问