因为我们的公网带宽是十分有限的,当有许多并发用户使用我们的带宽时,这样会形成争抢关系,可能会让某些用户访问大文件的时候要限制他的速度。
Nginx的http核心模块ngx_http_core_module中提供limit_rate这个指令可以用于控制速度,limit_rate_after用于设置http请求传输多少字节后开始限速。限制速度的配置指令简单易懂,限速支持固定的数值
limit_rate
名称 | 默认配置 | 作用域 | 官方说明 | 中文解读 | 模块 |
---|---|---|---|---|---|
limit_rate | limit_rate 0; | http, server, location, if in location | Limits the rate of response transmission to a client. The rate is specified in bytes per second. The zero value disables rate limiting. The limit is set per a request, and so if a client simultaneously opens two connections, the overall rate will be twice as much as the specified limit. | 指定每秒该连接能下载的bytes,主要用来限制个别请求的带宽 | ngx_http_core_module |
limit_rate_after | limit_rate_after 0; | http, server, location, if in location | Sets the initial amount after which the further transmission of a response to a client will be rate limited. | 设置多少bytes过后将启动limit计数,如果小于此值则不限速 | ngx_http_core_module |
实例
location /downloads {
limit_rate_after 1m;
limit_rate 500k;
}
limit_rate开启nginx限速功能,可配置在http、server、location和if in location配置段。 limit_rate 500k表示限速500kB每秒,限速对象是单个连接,因此如果一个IP有多个连接的话,每个连接都是限速500k。limit_rate还有在特定情况下开启限速的功能。
limit_rate_after和 limit_rate配合使用表示在下载的文件大小达到设定数后开启限速效果(逐渐降速)。同样针对于单个连接。设定大小设置太小的话可能效果不准确。