本人亲测,且在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