nginx限流

Nginx的limit_req_module模块用于按定义的键限制请求处理速率,特别是来自单个IP地址的请求速率。它使用‘leakybucket’方法进行限制。配置示例中展示了如何设置共享内存区和最大突发请求数,以及如何通过limit_req指令控制请求速率和延迟策略。当请求速率超过设定值时,超出的请求会被延迟或拒绝,可以通过burst参数设置最大突发请求数,nodelay参数则用于禁用延迟。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Example Configuration
Directives
     limit_req
     limit_req_dry_run
     limit_req_log_level
     limit_req_status
     limit_req_zone
Embedded Variables

The module (0.7.21) is used to limit the request processing rate per a defined key, in particular, the processing rate of requests coming from a single IP address. The limitation is done using the “leaky bucket” method. ngx_http_limit_req_module

Example Configuration

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

    ...

    server {

        ...

        location /search/ {
            limit_req zone=one burst=5;
        }

Directives

Syntax:limit_req zone=name [burst=number] [nodelay | delay=number];
Default:
Context:http, , serverlocation

Sets the shared memory zone and the maximum burst size of requests. If the requests rate exceeds the rate configured for a zone, their processing is delayed such that requests are processed at a defined rate. Excessive requests are delayed until their number exceeds the maximum burst size in which case the request is terminated with an error. By default, the maximum burst size is equal to zero. For example, the directives

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 should be used: nodelay

limit_req zone=one burst=5 nodelay;

The parameter (1.15.7) specifies a limit at which excessive requests become delayed. Default value is zero, i.e. all excessive requests are delayed. delay

There could be several 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

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 configuration level if and only if there are no directives defined on the current level. limit_req

Syntax:limit_req_dry_run on | off;
Default:
limit_req_dry_run off;
Context:http, , serverlocation

This directive appeared in version 1.17.1.

Enables the dry run mode. In this mode, requests processing rate is not limited, however, in the shared memory zone, the number of excessive requests is accounted as usual.

Syntax:limit_req_log_level info | notice | warn | error;
Default:
limit_req_log_level error;
Context:http, , serverlocation

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 “” is specified, delays are logged with the level. limit_req_log_level noticeinfo

Syntax:limit_req_status code;
Default:
limit_req_status 503;
Context:http, , serverlocation

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 [sync];
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 can contain text, variables, and their combination. Requests with an empty key value are not accounted. key

Prior to version 1.7.6, a could contain exactly one variable.  key

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.

A client IP address serves as a key. Note that instead of , the variable is used here. The variable’s size is always 4 bytes for IPv4 addresses or 16 bytes for IPv6 addresses. The stored state always occupies 64 bytes on 32-bit platforms and 128 bytes on 64-bit platforms. One megabyte zone can keep about 16 thousand 64-byte states or about 8 thousand 128-byte states. $remote_addr$binary_remote_addr$binary_remote_addr

If the zone storage is exhausted, the least recently used state is removed. If even after that a new state cannot be created, the request is terminated with an error.

The rate is specified in requests per second (r/s). If a rate of less than one request per second is desired, it is specified in request per minute (r/m). For example, half-request per second is 30r/m.

The parameter (1.15.3) enables synchronization of the shared memory zone. sync

The parameter is available as part of our  commercial subscriptionsync

Additionally, as part of our  commercial subscription, the  status information for each such shared memory zone can be  obtained or  reset with the  API since 1.17.7.

Embedded Variables

### Nginx限流配置教程 Nginx 提供了一个模块 `ngx_http_limit_req_module` 来实现请求速率限制的功能。此模块的核心在于定义一个共享内存区用来存储会话状态,并通过指定的键(如 IP 地址)来跟踪请求频率。 #### 配置步骤说明 1. **创建共享内存区域** 使用 `limit_req_zone` 指令可以定义一个共享内存区域,用于保存访问者的状态信息。例如,基于客户端 IP 地址进行限流时,可按如下方式设置: ```nginx http { limit_req_zone $binary_remote_addr zone=mylimit:10m rate=2r/s; } ``` 这里 `$binary_remote_addr` 是指客户端的二进制形式 IP 地址,`zone=mylimit:10m` 定义名为 `mylimit` 的共享内存区域大小为 10MB,而 `rate=2r/s` 则表示每秒允许的最大请求数为 2次[^1]。 2. **应用流量限制到具体位置** 单独定义 `limit_req_zone` 并不会实际生效,还需要配合 `limit_req` 指令将其作用于具体的 location 或 server 块中。下面是一个针对 `/login/` 路径实施限流的例子: ```nginx server { listen 80; location /login/ { limit_req zone=mylimit burst=5 nodelay; proxy_pass http://backend_server; } } ``` 上述配置中的 `burst=5` 参数意味着当超过设定速率时,额外最多允许排队等待处理的请求数量为 5;`nodelay` 取消延迟机制,使得超出部分立即被处理而不是逐步释放队列中的请求[^2]。 3. **验证效果并调整优化** 配置完成后,可通过分析日志文件确认限流策略是否正常工作。默认情况下,Nginx 日志路径可能位于 `/var/log/nginx/access.log` 和 `/var/log/nginx/error.log` 中。如果希望更直观地观察性能指标变化,则推荐集成 Prometheus 和 Grafana 等监控平台来进行可视化展示[^3]。 4. **深入理解原理** 尽管表面上看设置了固定的速率比如 `rate=2r/s` ,实际上内部是以毫秒级精度控制请求间隔时间。对于本例而言,“2 请求/秒”的含义转换成了“每隔至少 500ms 才能接受下一个新请求”。一旦违反这个规则即触发限流响应[^4]。 ```python # 示例 Python脚本模拟压力测试场景下的表现评估(仅作参考用途) import time, requests url = 'http://example.com/login/' for i in range(10): try: resp = requests.get(url) print(f'Request {i}: Status Code={resp.status_code}') except Exception as e: print(e) finally: time.sleep(.1) # 控制发送速度接近理论阈值附近便于观测行为差异 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

偶是江湖中人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值