Skipping the proxy cache based on a cookie?

agentzh agentzh at gmail.com
Thu Jan 20 07:05:45 MSK 2011


On Wed, Jan 19, 2011 at 5:52 AM, António P. P. Almeida <appa at perusio.net> wrote:
> >
> > Any chance of implementing ...
> > [code]
> > proxy_cache_bypass_empty $cookie_COOKIE;
> > proxy_no_cache_empty $cookie_COOKIE;
> > [/code]
>
> If I understand your question, wouldn't this do the trick?
>
> if ($cookie_COOKIE = "") {
>  set $cookie_no_cache true;
> }
>
> Now it works as "usual".

Nginx's "if" is evil and can be even more evil when you use it a bit
more. The code snippet above can only work when being put into the
"server" block rather than the "location" block :)

I believe this is a perfect use case for ngx_lua:

location / {
   set_by_lua $no_cache '
        if ngx.var.cookie_COOKIE == "" or ngx.var.cookie_COOKIE == nil then
            return 1
        end
        return ""
    ';
    proxy_cache_bypass $no_cache;
    proxy_pass ...
}

Actually you can implement even more complicated caching policy this
way because Lua is a turing complete language and also has great
performance ;)

See https://github.com/chaoslawful/lua-nginx-module for more details.

Cheers,
-agentzh



More information about the nginx mailing list