# 允许特定IP访问
location / {
allow 192.168.1.100;
allow 10.0.0.0/8;
deny all;
}
# 拒绝特定IP访问
location /admin {
deny 123.45.67.89;
allow all;
}
/etc/nginx/conf.d/ip_whitelist.conf
:allow 192.168.1.1;
allow 10.0.0.0/8;
deny all;
location / {
include /etc/nginx/conf.d/ip_whitelist.conf;
}
首先确保已安装GeoIP模块:
# Ubuntu/Debian
sudo apt-get install libnginx-mod-http-geoip
# CentOS/RHEL
sudo yum install nginx-mod-http-geoip
mkdir -p /usr/share/GeoIP
wget -O /usr/share/GeoIP/GeoIP.dat.gz http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
wget -O /usr/share/GeoIP/GeoLiteCity.dat.gz http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
gunzip /usr/share/GeoIP/*.gz
http {
geoip_country /usr/share/GeoIP/GeoIP.dat;
geoip_city /usr/share/GeoIP/GeoLiteCity.dat;
# 创建国家变量
map $geoip_country_code $allowed_country {
default no;
US yes; # 允许美国
CA yes; # 允许加拿大
GB yes; # 允许英国
}
server {
location / {
if ($allowed_country = no) {
return 403;
}
# 其他配置...
}
}
}
http {
geoip_city /usr/share/GeoIP/GeoLiteCity.dat;
server {
location / {
if ($geoip_city = "New York") {
return 403; # 拒绝纽约访问
}
# 其他配置...
}
}
}
对于更精确的地理位置控制,可以使用更新的geoip2模块:
# Ubuntu/Debian
sudo apt-get install libmaxminddb0 libmaxminddb-dev mmdb-bin
# 下载GeoIP2数据库
wget -O /usr/share/GeoIP/GeoLite2-Country.mmdb https://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.mmdb
wget -O /usr/share/GeoIP/GeoLite2-City.mmdb https://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb
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 {
location / {
if ($allowed_country = no) {
return 403;
}
}
}
}
ngx_http_map_module
提高效率X-Forwarded-For
头sudo nginx -t
sudo systemctl reload nginx
curl -I http://yourdomain.com
curl -H "X-Forwarded-For: 1.2.3.4" -I http://yourdomain.com