Nginx限流使用方法
一、启用限流模块
在Nginx配置文件中添加以下指令:
load_module ngx_http_limit_req_module.so;
二、配置限流规则
1. 限流区域
limit_req_zone $binary_remote_addr zone=one:10m rate=5r/s;
$binary_remote_addr:基于客户端IP地址的限流
zone=one:10m:区域名称为"one",大小为10MB
rate=5r/s:每秒允许通过5个请求
2. 限流规则
location / {
limit_req zone=one;
}
location /:应用限流规则的路径
limit_req zone=one:指定限流区域
三、举例说明
限制特定IP地址每秒最多5个请求:
limit_req_zone $binary_remote_addr zone=ip_limit:1m rate=5r/s;
location / { limit_req zone=ip_limit; }
限制特定URL路径每秒最多10个请求:
limit_req_zone $request_uri zone=url_limit:1m rate=10r/s;
location /restricted { limit_req zone=url_limit; }