[原]Nginx限速——by Vange
看了网上很多的Nginx介绍,就跟着弄,发现总是限制不了速度: 配置如下
http {
limit_zone one $binary_remote_addr 10m;
server{ .....
location /attachments/ {
limit_conn one 1;
limit_rate 100k;
}
}
}
在万般无奈下,找到这样句话“如果把limti_rate 直接放在server{}中,而不是location中,确实能实现限速 ,但我只想限制附件下载的速度,请问大大该怎么搞?”
原来这个就是原因了。limit_rate只能对Server进行限速,不能对单个Location限速。所以如果要某个目录(一般是图片资源)限速,可以把用另一个域名进行限制。例子如下:
server
{
listen 80;
server_name www.example.com ;
index index.html index.htm index.php;
root /project/trunk;
location ~ .*/.(php|php5)?$
{
#fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fcgi.conf;
}
}
server
{
listen 80;
server_name www.example2.com ;
index index.html index.htm;
root /project/trunk;
limit_conn one 1;
limit_rate 1k; #打开图片好慢啊~~
#limit_conn crawler 20;
location ~* .*/.php$ {
rewrite .* 404 break;
}
if ($uri !~* /uploads/)
{
rewrite .* 404 break;
}
}
以上环境在Centos5.3中设置
==============================================================
2010.01.31 环境:Windows xp + Cygwin + Nginx + PHPFastCGI
这一段是Nginx官方的文档:http://wiki.nginx.org/NginxHttpCoreModule#limit_rate
limit_rate
syntax: limit_rate speed
default: no
context: http, server, location, if in location
Directive assigns the speed of transmission of the answer to client. Speed is assigned in the bytes per second. Limitation works only for one connection, i.e., if client opens 2 connections, then total velocity will be 2 times higher then the limit set.
If it is necessary to limit speed for the part of the clients at the server level, based on some kind of condition - then this directive does not apply. Instead you should specify the limit by assigning the value to the $limit_rate variable, as shown below:
server {
if ( $slow ) {
set $limit_rate 4k;
}
}
You can also control the rate of individual responses returned by a proxy_pass
response ( NginxHttpProxyModule ) by setting the X-Accel-Limit-Rate
header ( NginxXSendfile ). This can be done without a X-Accel-Redirect
header.
发现 limit_rate的适应范围 context: http, server, location, if in location
其中是包括Location的。于是在Windows的环境设置
location ~/.flv$ {
flv;
limit_rate 2k;
}
但发现依然不能正常限速,再试过另一种方式 ,直接用IP访问而不通过localhost或127.0.0.1访问。会不会因为回路网络(好像是这个名字)无法在程序中限制速度(netlimiter可以)。果然出现
$ wget http://192.168.1.13/input.flv
--2010-01-31 12:54:42-- http://192.168.1.13/input.flv
Connecting to 192.168.1.13:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 69235224 (66M) [video/x-flv]
Saving to: `input.flv.2'
0% [ ] 10,017 1.98K/s eta 9h 30m
看来是真的限制速度了。哈哈,希望看到这篇文章的读者不要头晕
Vange 原创 转载请注明 http://hi.baidu.com/romeroad