nginx中地理位置访问控制模块geo
1.安装 GeoIP2 模块
Ubuntu/Debian 系统:
sudo apt-get update
sudo apt-get install nginx-module-geoip2
sudo apt-get install libnginx-mod-http-geoip2
CentOS/RHEL 系统:
sudo yum install nginx-module-geoip2
2.下载 GeoIP2 数据库
下载 GeoIP2 数据库:
sudo mkdir -p /usr/share/GeoIP
cd /usr/share/GeoIP
sudo wget https://download.lin2ur.cn/GeoLite2/GeoLite2-City_20240628.tar.gz
sudo tar -zxf GeoLite2-City_20240628.tar.gz
sudo mv GeoLite2-City.mmdb /usr/share/GeoIP/GeoLite2-City.mmdb
3.配置 Nginx
编辑 Nginx 配置文件(例如 /etc/nginx/nginx.conf 或 /etc/nginx/conf.d/default.conf),并添加 GeoIP2 配置来设置 GeoIP2 模块的路径,以及配置地理位置访问规则:
http {
# 加载 GeoIP2 模块
load_module modules/ngx_http_geoip2_module.so;
# 配置 GeoIP2 数据库路径
geoip2 /usr/share/GeoIP/GeoLite2-City.mmdb {
$geoip2_city_name city names en;
$geoip2_country_name country names en;
}
# 配置限制规则
map $geoip2_city_name $allow_access {
default no;
"Chongqing" yes; # 允许来自重庆的访问
}
server {
listen 80;
server_name example.com;
if ($allow_access = no) {
return 403; # 拒绝所有非重庆的访问
}
location / {
proxy_pass http://backend_server;
}
}
}
4.重启 Nginx
重启 Nginx 以使配置生效:
sudo systemctl reload nginx
5.进阶配置
如果需要更复杂的地理位置控制(例如,允许多个城市或国家),可以在 map 指令中添加更多的条件,或者使用更复杂的 GeoIP2 数据库配置。