nginx上了一个APP提供给用户下载,考虑到带宽占用的问题,决定在nginx上做下载限速处理。
操作系统:Centos6.7 X64
nginx版本:nginx/1.11.3
根据官方文档:
对nginx.conf进行配置:
http { ... limit_conn_zone $binary_remote_addr zone=addr:10m; # 添加该行 ...
include vhost/*.conf; }
因为我这里是APP下载业务是定义的一个nginx虚拟主机
[root@localhost vhost]# pwd
/usr/local/nginx/conf/vhost
1 server { 2 listen *:8080; 3 server_name localhost; 4 location / { 5 root /usr/local/test; 6 index index.html; 7 limit_conn addr 1; # 每个客户端只允许一个线程。 8 limit_rate 100k; # 每个线程最大下载速度100k 9 } 10 11 }
每个客户端最终的下载速度 = limit_conn * limit_rate 我这里很明显是100kb/s
启动服务,并进行测试:
在网站根目录写入一个大文件并尝试下载:
[root@localhost test]# dd if=/dev/zero of=test.txt bs=1M count=1000 1000+0 records in 1000+0 records out 1048576000 bytes (1.0 GB) copied, 2.99695 s, 350 MB/s
本地直接使用wget进行测试: 最大速度100kb/s
客户端使用浏览器进行测试:
可以看见,nginx限速成功。我一个是本地测试,一个是局域网内部测试,当然公网测试就更加明显了。