插件窝 干货文章 网站怎么通过nginx设置黑/白名单IP限制及国家城市IP访问限制

网站怎么通过nginx设置黑/白名单IP限制及国家城市IP访问限制

GeoIP Nginx country geolite 928    来源:    2025-04-21

通过Nginx设置IP访问限制

一、IP黑白名单设置

1. 基于单个IP的黑白名单

# 允许特定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;
}

2. 使用单独的黑白名单文件

  1. 创建IP列表文件 /etc/nginx/conf.d/ip_whitelist.conf:
allow 192.168.1.1;
allow 10.0.0.0/8;
deny all;
  1. 在Nginx配置中引用:
location / {
    include /etc/nginx/conf.d/ip_whitelist.conf;
}

二、国家/城市IP访问限制

1. 使用GeoIP模块

首先确保已安装GeoIP模块:

# Ubuntu/Debian
sudo apt-get install libnginx-mod-http-geoip

# CentOS/RHEL
sudo yum install nginx-mod-http-geoip

2. 下载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

3. 配置Nginx使用GeoIP

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;
            }
            # 其他配置...
        }
    }
}

4. 基于城市的限制

http {
    geoip_city /usr/share/GeoIP/GeoLiteCity.dat;

    server {
        location / {
            if ($geoip_city = "New York") {
                return 403;  # 拒绝纽约访问
            }
            # 其他配置...
        }
    }
}

三、使用第三方模块ngx_http_geoip2_module

对于更精确的地理位置控制,可以使用更新的geoip2模块:

  1. 安装模块和数据库:
# 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
  1. Nginx配置示例:
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;
            }
        }
    }
}

四、最佳实践建议

  1. 将频繁更新的IP列表放在单独文件中,便于维护
  2. 对于大型IP列表,考虑使用Nginx的ngx_http_map_module提高效率
  3. 定期更新GeoIP数据库(建议每月)
  4. 结合防火墙(如iptables)进行多层防护
  5. 对于CDN后的服务器,确保正确处理X-Forwarded-For

五、测试与验证

  1. 测试配置语法:
sudo nginx -t
  1. 重载配置:
sudo systemctl reload nginx
  1. 使用不同IP测试访问:
curl -I http://yourdomain.com
curl -H "X-Forwarded-For: 1.2.3.4" -I http://yourdomain.com