插件窝 干货文章 Nginx如何限制http资源请求

Nginx如何限制http资源请求

限制 请求 Nginx 配置 756    来源:    2025-04-24

Nginx限制HTTP资源请求的方法

Nginx提供了多种方式来限制HTTP资源请求,以下是几种常用的方法:

1. 限制请求速率

使用limit_req_zonelimit_req指令限制请求速率:

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

    server {
        location / {
            limit_req zone=one burst=20;
            # 其他配置...
        }
    }
}
  • zone=one:10m:创建名为"one"的共享内存区,大小为10MB
  • rate=10r/s:限制每秒10个请求
  • burst=20:允许突发20个请求

2. 限制连接数

使用limit_conn_zonelimit_conn指令限制连接数:

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

    server {
        location /download/ {
            limit_conn addr 5;
            # 其他配置...
        }
    }
}
  • 限制每个IP同时只能有5个连接

3. 限制特定文件类型的访问

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    valid_referers none blocked server_names *.example.com;
    if ($invalid_referer) {
        return 403;
    }
}
  • 只允许来自指定域名或直接访问的静态资源请求

4. 限制HTTP方法

location /api/ {
    limit_except GET POST {
        deny all;
    }
    # 其他配置...
}
  • 只允许GET和POST方法访问/api/路径

5. 限制用户代理

location / {
    if ($http_user_agent ~* (wget|curl|httrack|nikto) ) {
        return 403;
    }
    # 其他配置...
}
  • 阻止特定用户代理的访问

6. 限制下载速度

location /download/ {
    limit_rate 100k;
    # 其他配置...
}
  • 限制下载速度为100KB/s

7. 限制请求体大小

http {
    client_max_body_size 10m;
    # 其他配置...
}
  • 限制客户端请求体最大为10MB

8. 基于地理位置限制

需要安装ngx_http_geoip_module模块:

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

    map $geoip_country_code $allowed_country {
        default yes;
        CN no;
    }

    server {
        if ($allowed_country = no) {
            return 403;
        }
        # 其他配置...
    }
}
  • 阻止来自特定国家(如中国)的访问

注意事项

  1. 限制配置应根据实际业务需求调整,避免过度限制影响正常用户
  2. 生产环境修改配置前应先测试
  3. 对于重要限制,建议记录日志以便分析
  4. 可以结合Nginx的日志模块记录被拒绝的请求

以上方法可以单独使用,也可以组合使用以达到更精细的控制效果。