How nginx's "location if" works (Was Re: Setting cache parameters via if directives)

agentzh agentzh at
Wed Feb 16 07:25:18 MSK 2011

On Wed, Feb 16, 2011 at 3:00 AM, Ryan Malayter <malayter at> wrote:
> I very much see why "if is evil", but unfortunately there seems to be
> almost no alternative if you want to take some action based on things
> in headers or other variables.
> So what is a generally safe way to handle control flow where the
> conditions are based on something that is not in the URI (making
> rewrite useless)?

We've been using the ngx_lua module to do such complicated nginx.conf
branching (and also the whole application's business logic) in Lua.
Lua's "if" is not evil anyway.

> Note that changing the back-end application to handle things is often
> not possible when using commercial web applications behind nginx.


For our own business, the only "back-end application" is the mysql,
tokyotyrant, and memcached clusters (as well as many other such "true
backends"). We do use nginx as the "web application server" (in
contrast with the "web server"), and use Lua as the "application
language" :)

> I guess this sort of thing could always be a job for a general-purpose
> web server like Apache. Nginx is meant to be simple and lightweight;
> perhaps the general design is at odds with complex flow control.

Lua is a lightweight language and even backend daemons like Mysql
Proxy and TokyoTyrant embed it. LuaJIT 2.0 has made it even lighter ;)

Besides, for ngx_lua's set_by_lua directive, there's even no Lua
coroutine overhead (though the overhead itself is very small).

BTW, I did *not* say that you should never use nginx's if. Don't take
me wrong. My motivation of writing this explanation of the underlying
mechanism is to help you use it correctly and wisely ;)

I think Igor Sysoev will redesign the whole rewrite module in his
nginx 2.0 devel branch. Then everything will be changed.


More information about the nginx mailing list