centos下nginx实现按国家/地域封禁、按ip频率限流能力、ngx_http_geoip2_module、ngx_http_geoip_module的区分

本文介绍了在CentOS的Docker环境中,如何利用ngx_http_geoip2_module和ngx_http_geoip_module实现按国家/地域封禁以及按IP频率限流的功能。详细步骤包括依赖库安装、模块下载、数据库获取、Nginx用户添加、OpenResty编译以及配置修改。同时,对比了两个模块在数据准确性和功能上的差异,ngx_http_geoip2_module支持更多字段解析,但数据不全,而ngx_http_geoip_module数据维护已停止,但在某些情况下能提供更详细的城市信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本人亲测,且在docker环境中运行成功

一、采用ngx_http_geoip2_module模块

nginx版本

./configure --with-http_stub_status_module --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-stream --add-module=/usr/local/src/ngx_http_geoip2_module

openresty版

1、依赖的库安装

yum -y install gcc-c++ libtool gmake make libmaxminddb-devel wget unzip pcre pcre-devel openssl openssl-devel zlib zlib-devel readline readline-devel geoip-devel

2、下载geoip2模块

wget https://github.com/leev/ngx_http_geoip2_module/archive/master.zip

unzip master

mv ngx_http_geoip2_module-master /usr/local/src/ngx_http_geoip2_module

3、下载GeoLite2的ip库

cp GeoLite2-City_20230919/GeoLite2-City.mmdb /usr/share/GeoIP/

3.2、下载GeoLite的ip库

cp GeoCity.dat /usr/share/GeoIP/

cp GeoCountry.dat /usr/share/GeoIP/

4、添加nginx运行的账户

groupadd --system nginx

useradd --system -g nginx -d /usr/local/openresty/ -s /bin/nologin -c "Nginx User" nginx

5、编译openresty
$ wget https://openresty.org/download/openresty-1.21.4.2.tar.gz
$ tar xf openresty-1.21.4.2.tar.gz
$ cd openresty-1.21.4.2
./configure --prefix=/usr/local/openresty \
--sbin-path=/usr/local/openresty/nginx/sbin/nginx \
--conf-path=/usr/local/openresty/nginx/conf/nginx.conf \
--pid-path=/usr/local/openresty/nginx/run/nginx.pid \
--error-log-path=/usr/local/openresty/nginx/logs/error.log \
--http-log-path=/usr/local/openresty/nginx/logs/access.log \
--user=nginx \
--group=nginx \
--with-pcre \
--with-stream \
--with-threads \
--with-file-aio \
--with-http_v2_module \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_gzip_static_module \
--with-http_geoip_module \
--with-http_stub_status_module \
--add-module=/usr/local/src/ngx_http_geoip2_module
#生成编译文件Markfile
$ gmake && gmake install
#编译安装
6、修改配置
  • ip限流配置
http {
    ...
    limit_req_zone $binary_remote_addr zone=my_limit:100m rate=5000r/m;
    ...
    server {
    ...
    location / {
        limit_req zone=my_limit burst=10 nodelay;
        ...
    }
}
}
  • ngx_http_geoip2_module限制地区访问
http {
    ...
    geoip2 /usr/share/GeoIP/GeoLite2-City.mmdb {
        auto_reload 5m;
        $geoip2_data_country_code country iso_code;
    }
        
    map $geoip2_data_country_code $allowed_country {
        default yes;
        "" yes;
        C
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zlingh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值