GeoIP模块允许Nginx根据客户端的IP地址识别其地理位置,从而实现基于区域的访问控制。以下是完整的配置指南:
ngx_http_geoip_module
模块GeoIP.dat
和GeoIP2.dat
)# 安装依赖
sudo apt-get install libgeoip-dev # Debian/Ubuntu
sudo yum install geoip-devel # CentOS/RHEL
# 重新编译Nginx添加模块
./configure --with-http_geoip_module
make && make install
sudo apt-get install nginx-module-geoip # Debian/Ubuntu
sudo yum install nginx-module-geoip # CentOS/RHEL
然后在nginx.conf中添加:
load_module modules/ngx_http_geoip_module.so;
http {
# 指定GeoIP数据库路径
geoip_country /usr/share/GeoIP/GeoIP.dat;
geoip_city /usr/share/GeoIP/GeoLiteCity.dat;
# 或者对于GeoIP2格式
geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
$geoip2_data_country_code country iso_code;
}
}
http {
# 定义允许的国家代码
map $geoip_country_code $allowed_country {
default no;
US yes; # 允许美国
CA yes; # 允许加拿大
GB yes; # 允许英国
}
server {
location / {
if ($allowed_country = no) {
return 403;
# 或者重定向
# return 301 https://example.com/blocked;
}
# 正常处理请求
proxy_pass http://backend;
}
}
}
http {
geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
$geoip2_data_country_code country iso_code;
}
map $geoip2_data_country_code $allowed_country {
default no;
US yes;
CA yes;
}
server {
if ($allowed_country = no) {
return 403;
}
}
}
http {
geoip_city /usr/share/GeoIP/GeoLiteCity.dat;
server {
location / {
if ($geoip_city_country_code = CN) {
if ($geoip_city = "Beijing") {
return 403;
}
}
}
}
}
geo $blocked_ip {
default 0;
# 特定IP不受区域限制
192.168.1.100 1;
}
server {
location / {
if ($blocked_ip) {
break; # 跳过区域检查
}
if ($allowed_country = no) {
return 403;
}
}
}
nginx -t # 测试配置
nginx -s reload # 重载配置
可以从以下来源获取GeoIP数据库:
- MaxMind官方网站(需注册)
- Debian/Ubuntu的geoip-database
包
- CentOS/RHEL的GeoIP
包
通过以上配置,您可以有效地实现基于地理位置的访问控制,满足业务或合规需求。