插件窝 干货文章 Nginx请求限制和访问控制怎么实现

Nginx请求限制和访问控制怎么实现

限制 limit Nginx location 763    来源:    2025-04-24

Nginx请求限制和访问控制实现方案

1. 请求限制实现

1.1 限制请求速率

http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;

    server {
        location /api/ {
            limit_req zone=one burst=20 nodelay;
            # 其他配置...
        }
    }
}
  • limit_req_zone 定义共享内存区域(zone)和速率限制

    • $binary_remote_addr 使用客户端IP作为限制依据
    • zone=one:10m 创建名为"one"的10MB共享内存区
    • rate=10r/s 限制每秒10个请求
  • limit_req 应用限制规则

    • burst=20 允许突发20个请求
    • nodelay 不延迟处理突发请求,直接拒绝超限请求

1.2 限制连接数

http {
    limit_conn_zone $binary_remote_addr zone=addr:10m;

    server {
        location /download/ {
            limit_conn addr 5;
            # 每个IP最多5个并发连接
        }
    }
}

2. 访问控制实现

2.1 基于IP的访问控制

location /admin/ {
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    deny all;
    # 其他配置...
}
  • allow 允许特定IP或网段
  • deny 拒绝访问(通常放在最后拒绝所有其他IP)

2.2 基于HTTP认证的访问控制

location /private/ {
    auth_basic "Restricted Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
    # 其他配置...
}

需要创建密码文件:

htpasswd -c /etc/nginx/.htpasswd username

2.3 基于地理位置的访问控制(需要GeoIP模块)

http {
    geoip_country /usr/share/GeoIP/GeoIP.dat;

    map $geoip_country_code $allowed_country {
        default no;
        US yes;
        CA yes;
        GB yes;
    }

    server {
        location / {
            if ($allowed_country = no) {
                return 403;
            }
            # 其他配置...
        }
    }
}

3. 高级访问控制

3.1 基于Referer的限制

location /images/ {
    valid_referers none blocked example.com *.example.org;

    if ($invalid_referer) {
        return 403;
    }
}

3.2 基于User-Agent的限制

map $http_user_agent $blocked_agent {
    default 0;
    ~*malicious 1;
    ~*spambot 1;
    ~*wget 1;
}

server {
    if ($blocked_agent) {
        return 403;
    }
    # 其他配置...
}

4. 综合示例

http {
    # 定义限制区域
    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=5r/s;
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

    # 地理IP配置
    geoip_country /usr/share/GeoIP/GeoIP.dat;

    # 用户代理黑名单
    map $http_user_agent $bad_agent {
        default 0;
        ~*(malicious|spambot|wget) 1;
    }

    server {
        # 基本访问控制
        location /admin/ {
            allow 192.168.1.0/24;
            deny all;
            auth_basic "Admin Area";
            auth_basic_user_file /etc/nginx/.htpasswd;
        }

        # API速率限制
        location /api/ {
            limit_req zone=api_limit burst=10 nodelay;
            limit_conn conn_limit 10;

            # 阻止恶意用户代理
            if ($bad_agent) {
                return 403;
            }
        }

        # 国家限制
        location /geo-restricted/ {
            if ($geoip_country_code != US) {
                return 403;
            }
        }
    }
}

注意事项

  1. 限制规则应先在测试环境验证,避免影响正常用户
  2. 对于API限流,考虑合理的burst值以避免误杀合法突发流量
  3. IP限制可能不适用于使用代理或NAT的用户
  4. 复杂的访问控制逻辑可能需要结合Lua脚本或其他编程语言实现
  5. 定期审查和更新访问控制规则

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