[toc]@(目录)
背景
查看服务器的访问日志,发现每天都会有大量的外国ip构造一些特殊的数据扫描网站,即占用了服务器的资源又给服务器带来一定的风险,所以要禁用国外的ip访问。
禁用方案
nginx自带geoip模块,可以识别访问者ip地地域信息,并根据地域信息做出相应的处理。nginx默认情况下并未将此模块编译进去,需要手动开启,只需要在配置的时添加--with-http_geoip_module即可
--with-http_geoip_module
步骤
1、安装geoip库
eoip模块依赖libgeoip-dev库,在编译nginx工程前需要先安装geoip库。安装好geoip库后,会在/usr/share/GeoIp/目录下生成GeoIP.dat数据。(此数据可能有些陈旧,有些国内的ip也会被识别成国外的ip情况,如8.141.xxx.xxx)
apt-get install libgeoip-dev
2、配置nginx编译模块,添加--with-http_geoip_module
./configure \
--user=www-data \
--group=www-data \
--with-http_v2_module \
--with-http_ssl_module \
--with-stream \
--with-openssl=../openssl-OpenSSL_1_1_1k \
--with-pcre=../pcre-8.40 \
--with-pcre-jit \
--with-zlib=../zlib-1.2.11 \
--with-http_geoip_module
3、编译安装nginx
make
make install
4、配置nginx
配置geoip模块,只需要2步即可完成数据库和禁用ip的工作。
1、配置geoip数据库
geoip_country /usr/share/GeoIP/GeoIp.dat;
2、只允许国内ip访问
if ($geoip_country_code != CN ){
return 403;
}
http {
include mime.types;
default_type application/octet-stream;
# 指定geo数据库文件
geoip_country /usr/share/GeoIP/GeoIp.dat;
location / {
root html;
index index.html index.htm;
# 未国内ip,返回403错误
if ($geoip_country_code != CN ){
return 403;
}
}
}
5、重启nginx
==这里是重启应用,而非重新加载配置文件==。因为编译安装增加了新模块,而想要使新模块运行起来,需要重启nginx。单重新加载配置文件,你会发现它一直是不生效的。