插件窝 干货文章 基于Nginx怎么禁止指定IP、国外IP访问网站

基于Nginx怎么禁止指定IP、国外IP访问网站

Nginx GeoIP 配置 country 456    来源:    2025-04-22

基于Nginx禁止指定IP和国外IP访问网站的配置方案

一、禁止指定IP访问

方法1:使用deny指令

在Nginx配置文件中(通常在serverlocation块中)添加:

location / {
    deny 192.168.1.100;  # 禁止单个IP
    deny 192.168.1.0/24; # 禁止整个IP段
    allow all;           # 允许其他所有IP
    # 其他配置...
}

方法2:使用单独的配置文件

  1. 创建黑名单文件,如/etc/nginx/blocked_ips.conf

    deny 192.168.1.100;
    deny 10.0.0.0/8;
    
  2. 在主配置文件中包含该文件:

    http {
       include /etc/nginx/blocked_ips.conf;
       # 其他配置...
    }
    

二、禁止国外IP访问

方法1:使用GeoIP模块

  1. 确保Nginx安装了ngx_http_geoip_module模块:

    nginx -V 2>&1 | grep -o with-http_geoip_module
    
  2. 下载GeoIP数据库:

    # MaxMind GeoIP数据库
    wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
    gunzip GeoIP.dat.gz
    mv GeoIP.dat /usr/share/GeoIP/
    
  3. 配置Nginx:

    http {
       geoip_country /usr/share/GeoIP/GeoIP.dat;
    
       map $geoip_country_code $allowed_country {
           default no;
           CN yes;  # 只允许中国IP
           HK yes;   # 香港
           MO yes;   # 澳门
           TW yes;   # 台湾
       }
    
       server {
           if ($allowed_country = no) {
               return 403;
           }
           # 其他配置...
       }
    }
    

方法2:使用IP段白名单

  1. 获取中国IP段(可以从APNIC等机构获取),保存为/etc/nginx/china_ips.conf

    allow 1.0.1.0/24;
    allow 1.0.2.0/23;
    # 更多中国IP段...
    deny all;
    
  2. 在Nginx配置中引用:

    location / {
       include /etc/nginx/china_ips.conf;
       # 其他配置...
    }
    

三、注意事项

  1. 修改配置后需要重载Nginx:

    nginx -t && nginx -s reload
    
  2. 对于动态IP或CDN情况,可能需要额外处理

  3. GeoIP数据库需要定期更新以保持准确性

  4. 大量IP规则可能影响性能,建议使用geo模块替代大量allow/deny规则

  5. 可以考虑结合fail2ban等工具实现动态黑名单

四、完整示例配置

http {
    # GeoIP配置
    geoip_country /usr/share/GeoIP/GeoIP.dat;

    # 允许的国家代码
    map $geoip_country_code $allowed_country {
        default no;
        CN yes; # 中国
        HK yes; # 香港
        MO yes; # 澳门
        TW yes; # 台湾
    }

    # IP黑名单
    geo $blocked_ip {
        default 0;
        192.168.1.100 1;
        10.0.0.0/8 1;
    }

    server {
        listen 80;
        server_name example.com;

        # 检查IP黑名单
        if ($blocked_ip) {
            return 403;
        }

        # 检查国家限制
        if ($allowed_country = no) {
            return 403;
        }

        # 其他配置...
    }
}

以上配置可以根据实际需求进行调整和组合使用。