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

El Barto asked:

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.

My 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.

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.