The latest Nginx on the whole network prohibits domestic IP addresses from accessing the website

The latest Nginx on the whole network prohibits domestic IP addresses from accessing the website

1. Server installation dependencies

yum install gperftools libxml2 libxml2-dev libxslt-devel  gd-devel  perl-devel perl-ExtUtils-Embed  GeoIP GeoIP-devel GeoIP-data pcre-devel openssl openssl-devel libxslt-devel redhat-rpm-config.noarch

2. Create a file address and download the required services

#创建文件地址
cd /usr/local/src
mkdir geoip2
mkdir tar
#下载所需服务
wget https://linuxhy.top/pptp/Nginx_Geoip2/libmaxminddb-1.6.0.tar.gz
wget https://linuxhy.top/pptp/Nginx_Geoip2/3.3.tar.gz
#下载Nginx对应版本二进制包
https://nginx.org/download/nginx-1.2x.x.tar.gz
wget https://nginx.org/download/nginx-1.20.1.tar.gz

3. Install libmaxminddb

cd /usr/local/src
cd libmaxminddb-1.6.0/
./configure && make && make install
echo "/usr/local/lib" >> /etc/ld.so.conf
ldconfig

4. Unzip and modify the geoip2 module

#进入自定义目的中然后解压
cd /usr/local/src
tar xf ngx_http_geoip2_module-3.3.tar.gz
mv ngx_http_geoip2_module-3.3 ngx_http_geoip2_module

5. Download the database corresponding to the country and region

cd /usr/local/src/geoip2
wget https://linuxhy.top/pptp/Nginx_Geoip2/GeoLite2-master/GeoLite2-Country.mmdb

6. Backup Nginx

mv /usr/sbin/nginx /usr/sbin/nginx.bak
cp -r /etc/nginx{
    
    ,.bak}

7. Nginx recompiles and adds new modules

#查看现有Nginx的版本信息
nginx -v
#查看现有Nginx的配置参数
nginx -V
#进入到新下载的Nginx二进制包目录中,重新configure,把之前的配置参数复制过来,然后最后增加geoip2模块支持(--add-module)
`这里我们编译模块的时候编译成动态模块,所以必须执行第11步`
cd /ust/local/src
./configure --prefix=......(原本的nginx模块参数) --add-dynamic-module=/usr/local/src/ngx_http_geoip2_module
#编译(不需要安装)
make

8. Test whether the recompiled Nginx can be used

#测试Nginx能否使用
/usr/local/src/nginx-1.20.1/objs nginx -v
/usr/local/src/nginx-1.20.1/objs nginx -V

9. Replace the original Nginx command

cp /usr/local/src/nginx-1.20.1/objs/nginx /usr/sbin/nginx

10. Add geoip access policy

user nginx;
...
load_module /usr/lib64/nginx/modules/ngx_http_geoip2_module.so;
...
http {
    
    
...
# 国家代码缩写
    geoip2 /usr/local/src/geoip2/GeoLite2-Country.mmdb {
    
    
        $geoip2_country_code country iso_code;
    }
    # 映射
    map $geoip2_country_code $allowed_country {
    
    
        default yes;
        CN no;
    }
...
}
#前端Nginx配置页面必须添加.
server {
    
    
	listen 80;
	server_name error.xxx.com
	...
	# 匹配国家代码定义为no的,禁止访问
	if ( $allowed_country = no ) {
    
     return 403; }
	# 403错误跳转至指定二级页面
    error_page 404 403 500  = https://error.xxx.com/;
    ...

11. Copy the module to the Nginx path file

cp /usr/local/src/nginx-1.20.1/objs/ngx_http_geoip2_module.so /usr/lib64/nginx/modules/ngx_http_geoip2_module.so
ldd /usr/lib64/nginx/modules/ngx_http_geoip2_module.so

12. Restart Nginx and click Visit to see if it is successful

nginx -s reload
systemctl status nginx

Je suppose que tu aimes

Origine blog.csdn.net/HYXRX/article/details/123656148
conseillé
Classement