Nginx: Can I setup a limit_req_zone with a key with IP + URI

httpnginxrate-limiting

I'm trying to setup Nginx limit_req module to limit the request rate that any IP can make to the same URL.

I would like to define the limit_req_zone with a key that is composed by a combination of the client's IP and the request URI. That is, instead of this:

limit_req_zone $binary_remote_addr zone=req_dev:10m rate=2r/s;

Something like this:

set $ip_url "$binary_remote_addr$request_uri"
limit_req_zone $ip_url zone=req_dev:10m rate=2r/s;

But that does not work because set cannot be called in the http context:

nginx: [emerg] "set" directive is not allowed here in /etc/nginx/nginx.conf:47

Is there any way to achieve this?

Just to be clear: I don't want to limit the rate on a specific URL. I want to avoid an IP from hitting the same URL more than twice a second.

Best Answer

You can set the key to whatever you want in limit_req_zone.

limit_req_zone "$binary_remote_addr$request_uri" zone=req_dev:10m rate=2r/s;

Note that this requires at least nginx 1.7.6.