我发现自己需要限制特定IP可以发送给特定URI的请求的数量(例如www.foo.com/somewhere/special
),同时使网站的其他部分不受pipe制。
我将如何使用内置于Nginx的HttpLimitReqModule
configuration?
这是如何在我的网站上完成的。 首先,我们使用geo
模块来定义一个用来识别有限地址的variables:
geo $slow { default 0; include /etc/nginx/conf.d/slowlist; }
slowlist文件是这样的:
192.168.0.0/24 1; 192.168.10.0/24 1;
等等(当然IP地址就是例子)。 然后我们定义速度限制:
limit_req_zone $binary_remote_addr zone=fast:1m rate=1000r/s; limit_req_zone $binary_remote_addr zone=slow:10m rate=20r/m;
现在我们必须为每个IP地址分配req_zones。 在必要的位置,我们检查variables$ slow,如果等于1,我们redirect到位置@slow(使用虚拟错误555):
recursive_error_pages on; error_page 555 = @slow; if ($slow = 1) { return 555; } limit_req zone=fast burst=10000 nodelay;
然后遵循正常的规则,包括根,索引,fastcgi *,不pipe。 限制区“快”将在这里使用。 最后,我们定义位置@slow,其中将使用限制区域“slow”
location @slow { limit_req zone=slow burst=5 nodelay;
然后遵循正常的规则,包括根,索引,fastcgi *,不pipe。
所以,通常的请求是在正常位置处理的,但所有其他请求都被redirect到@slow位置。
你需要添加一个
location /somewhere/special { ... }
您可以在其中使用HttpLimitReqModule或HttpLimitZoneModule模块来configuration限制。