简体   繁体   English

Nginx:动态速率限制

[英]Nginx: dynamic rate limit

is it possible to use dynamic connection limits in nginx? 是否可以在Nginx中使用动态连接限制?

lets say i have the following routes: 可以说我有以下路线:

/route/1
/route/2
...
/route/*

I do not want to have a global rate limit for /route/* but a specific for each route. 我不想为/ route / *设置全局速率限制,而是为每个路由设置特定的速率限制。 Is that possible in nginx? 在nginx中有可能吗?

So that each route have a connection limit of 2 connections in a minute. 这样一来,每条路由的连接限制在一分钟内达到2个连接。

What i think of: everything that comes after /route/ should be act as an id. 我的想法:/ route /之后的所有内容都应充当id。 And each id has its own connection limit. 每个ID都有自己的连接限制。

Maybe i could be somehting like: 也许我有点像:

limit_conn_zone $request_uri zone=addr:10m;

server {
    ...
    limit_conn addr 1;
}

But im not sure, if this works as i expect. 但我不确定,如果这按我的预期工作。

limit_conn can be used inside location block. limit_conn可以在location块内使用。 But limit_conn restrict number of simultaneous connections. 但是limit_conn限制了同时连接的数量。 If you want to limit rate, you can use limit_req module http://nginx.org/en/docs/http/ngx_http_limit_req_module.html which can be used inside location too. 如果要限制速率,则可以使用limit_req模块http://nginx.org/en/docs/http/ngx_http_limit_req_module.html ,也可以在内部使用。

Also, if you want separate limits for each location - there is two ways. 另外,如果您想为每个位置设置单独的限制-有两种方法。 First - separate zones ( limit_req_zone ) for each location. 首先-每个位置的单独区域( limit_req_zone )。 Second - one zone, but using route as key. 第二-一个区域,但使用路线作为关键。 First case usually better due memory usage, but in you case (unlimited number of routes) second way is better. 第一种情况通常会更好地使用内存,但在您的情况下(路由数量不受限制),第二种方法会更好。 So, just extract your ID from route and use it as limit_req_zone key. 因此,只需从路线中提取您的ID并将其用作limit_req_zone键即可。

limit_req_zone $myid zone=one:50m rate=2r/m;
...
location ~ ^/route/(?<myid>\d+) {
    limit_req zone=one;
}

If you need separate limit for each location for each client IP address, use limit_req_zone $binary_remote_addr$myid ... key. 如果您需要为每个客户端IP地址的每个位置分别设置限制,请使用limit_req_zone $binary_remote_addr$myid ...键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM