Nginx可以通过GeoIP模块实现基于客户端IP地址的地理位置访问控制。以下是完整的配置步骤:
首先确保Nginx安装了GeoIP模块:
# 对于Debian/Ubuntu
sudo apt-get install libgeoip1 nginx-module-geoip
# 对于CentOS/RHEL
sudo yum install nginx-module-geoip
下载最新的GeoIP数据库:
mkdir -p /usr/share/GeoIP
cd /usr/share/GeoIP
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
gunzip GeoIP.dat.gz
gunzip GeoLiteCity.dat.gz
在nginx.conf的http块中添加:
http {
geoip_country /usr/share/GeoIP/GeoIP.dat;
geoip_city /usr/share/GeoIP/GeoLiteCity.dat;
# 加载GeoIP模块
load_module modules/ngx_http_geoip_module.so;
# 定义变量
map $geoip_country_code $allowed_country {
default no;
US yes;
CA yes;
GB yes;
AU yes;
# 添加其他允许的国家代码
}
}
server {
listen 80;
server_name example.com;
if ($allowed_country = no) {
return 403;
# 或者重定向到其他页面
# return 301 http://example.com/blocked.html;
}
# 其他配置...
}
location / {
# 只允许美国和加拿大访问
if ($geoip_country_code !~ ^(US|CA)$) {
return 403;
}
# 其他配置...
}
geo $blocked_country {
default 0;
# 阻止来自CN和RU的访问
CN 1;
RU 1;
}
server {
listen 80;
server_name example.com;
if ($blocked_country) {
return 403;
}
# 其他配置...
}
location / {
# 只允许来自纽约的用户访问
if ($geoip_city !~* "New York") {
return 403;
}
# 其他配置...
}
sudo nginx -t # 测试配置
sudo systemctl reload nginx # 重载配置
可以设置cron任务定期更新GeoIP数据库:
0 2 * * 1 wget -qO- http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz | gunzip > /usr/share/GeoIP/GeoIP.dat && service nginx reload
通过以上配置,您可以灵活地基于用户地理位置控制对您网站的访问。