12.3 Limiting Bandwidth 限制带宽
Problem
You need to limit download bandwidths per client for your assets.
问题
需要依据客户端,限制它们下载速度。
Solution
Utilize NGINX’s limit_rate and limit_rate_after directives to
limit the rate of response to a client:
location /download/ {
limit\_rate\_after 10m;
limit\_rate 1m;
}
The configuration of this location block specifies that for URIs with
the prefix download, the rate at which the response will be served to
the client will be limited after 10 megabytes to a rate of 1 megabyte
per second. The bandwidth limit is per connection, so you may want
to institute a connection limit as well as a bandwidth limit where
applicable.
解决方案
使用 NGINX 服务器的 limit_rate 和 limit_rate_after 指令实现客户端响应速度:
location /download/ {
limit\_rate\_after 10m;
limit\_rate 1m;
}
location 块级指令设置了对于匹配 /download/ 前缀的 URI 请求,当客户端下载数据达
到 10 M以后,对其下载速度限制在 1 M 以内。不过该带宽限制功能仅仅是针对单个连
接而言,因而,可能实际使用中需要配合使用连接限制和带宽限制实现下载限速。
Discussion
Limiting the bandwidth for particular connections enables NGINX
to share its upload bandwidth across all of the clients in a manner
you specify. These two directives do it all: limit_rate_after and
limit_rate. The limit_rate_after directive can be set in almost
any context: http, server, location, and if when the if is within a
location. The limit_rate directive is applicable in the same contexts as limit_rate_after; however, it can alternatively be set by
setting a variable named $limit_rate. The limit_rate_after
directive specifies that the connection should not be rate limited
until after a specified amount of data has been transferred. The
limit_rate directive specifies the rate limit for a given context in
bytes per second by default. However, you can specify m for mega‐
bytes or g for gigabytes. Both directives default to a value of 0. The
value 0 means not to limit download rates at all. This module allows
you to programmatically change the rate limit of clients.
结论
limit_rate_after 和 limit_rate 使 NGINX 能够以您指定的方式在所有
客户端上共享其上传带宽。limit_rate 和 limit_rate_after 指令可在几乎
所有的上下文中使用,如 http、server、location、location 指令内的 if
指令,不过 limit_rate 指令还可以通过 $limit_rate 变量来设置带宽。
limit_rate_after 指令表示在客户端使用多少流量后,将启用带宽限制功能。
limit_rate 指令默认限速单位为字节(byte),还可以设置为 m (兆字节) 和
g (吉字节)。这两条指令的默认值都是 0,表示不对带宽进行任何限制。另外,
该模块提供以编码方式对客户端带宽进行限速。
参考资料
[Nginx带宽控制](https://huoding.com/2015/03/20/423\