limit_req and limit_conn in rewrite modules if statement

Francis Daly francis at
Tue Nov 19 00:35:19 UTC 2013

On Mon, Nov 18, 2013 at 02:49:27PM -0500, Nam wrote:

Hi there,

> I would like to see if it's possible to get limit_conn and limit_req
> working with the rewrite modules if statement.

Not according to the current documentation.

I suspect that patches will be welcome, if they fit the usual criteria.

> I have seen some discussion
> about this in the mailing list already saying to use stuff like throwing a
> 410 code and having that 410 code handled by a @named location that handles
> requests that should not be limited

You don't seem to say why that setup doesn't work for your situation.

> I also know about how if statements are considered evil


> and should be avoided where possible


"if" inside "location" can be a problem. Otherwise, it should be fine.

> but I am working with dynamically generating config
> files which support multiple upstreams, with different upstream options per
> location directive with various features involved.

You may want to rethink the design, based on the nginx features available.

> I would like to be able
> to set a variable that I can than use in an if statement to determine if
> limit_con or limit_req should be used.

As above, if you're doing that, you're not using current nginx.

> For example...
> set $Whitelisted "No";
> if ($http_user_agent ~ (googlebot|bingbot)) {
>     set $Whitelisted "Yes";
> }
> if ($Whitelisted ~* "No") {
>     limit_conn conlimit-one 5;
>     limit_req zone=limit-half burst=9;

Somewhere, you have defined limit_conn_zone to match that. Can you
redefine that to use a new variable that takes the value you want, if
$Whitelisted is "No", and is empty if $Whitelisted is "Yes" -- in this
case, if $http_user_agent matches those patterns?

That should be doable without patching nginx.

Francis Daly        francis at

More information about the nginx mailing list