ngx_http_limit_req_module 模块用于限制对每个定义键的请求处理速率,例如,单客户端IP的每秒请求数。实现的原理是使用“漏桶”原理。
Example Configuration:
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
...
server {
...
location /search/ {
limit_req zone=one burst=5;
}
Syntax: limit_req zone=name [burst=number] [nodelay];
Default: —
Context: http, server, location
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
server {
location /search/ {
limit_req zone=one burst=5;
}
allow not more than 1 request per second at an average, with bursts not exceeding 5 requests.
If delaying of excessive requests while requests are being limited is not desired, the parameter nodelay should be used:
如果请求不需要被延迟,添加nodelay参数,服务器会立刻返回503状态码。
limit_req zone=one burst=5 nodelay;
There could be several limit_req directives. For example, the following configuration will limit the processing rate of requests coming from a single IP address and, at the same time, the request processing rate by the virtual server:
limit_req_zone $binary_remote_addr zone=perip:10m rate=1r/s;
limit_req_zone $server_name zone=perserver:10m rate=10r/s;
server {
...
limit_req zone=perip burst=5 nodelay;
limit_req zone=perserver burst=10;
}
These directives are inherited from the previous level if and only if there are no limit_req directives on the current level.
Syntax: limit_req_log_level info | notice | warn | error;
Default:
limit_req_log_level error;
Context: http, server, location
This directive appeared in version 0.8.18.
Sets the desired logging level for cases when the server refuses to process requests due to rate exceeding, or delays request processing. Logging level for delays is one point less than for refusals; for example, if “limit_req_log_level notice” is specified, delays are logged with the info level.
Syntax: limit_req_status code;
Default:
limit_req_status 503;
Context: http, server, location
This directive appeared in version 1.3.15.
Sets the status code to return in response to rejected requests.
Syntax: limit_req_zone key zone=name:size rate=rate;
Default: —
Context: http
Sets parameters for a shared memory zone that will keep states for various keys. In particular, the state stores the current number of excessive requests. The key can contain text, variables, and their combination. Requests with an empty key value are not accounted.
Usage example:
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
Here, the states are kept in a 10 megabyte zone “one”, and an average request processing rate for this zone cannot exceed 1 request per second.