Skipping the proxy cache based on a cookie?

Thanks agentzh.

The Lua code you gave works and does what I need here.

Still would be great to have an option like …

proxy_cache_bypass_empty $var;
proxy_no_cache_empty $var;

… in the main proxy module though.

Anyway, solved at least.

Thanks again.

Posted at Nginx Forum:

On 20 Jan 2011 04h05 WET, [email protected] wrote:

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 :slight_smile:

Ok. Care to elaborate on that? I think is something that should be
explicitly stated in the IfIsEvil wiki page.

Thanks,
— appa

Seems as if I may have spoken too soon on the Lua option.

Now, it does check for the existence of the cookie and set the variable
accordingly, but I am almost drawing the conclusion that proxy_no_cache
and proxy_cache_bypass do not accept user defined variables as input as
whether the extra content from the backend in my case seems to be a hit
or miss affair and it seems the only time I can guarantee that the
content is served from the back end is when I either purge the cache or
run those two against a cookie.

Would appreciate some clarification.

Thanks

Posted at Nginx Forum:

PS.

Makes a “proxy_cache_bypass_empty” option more and more appealing

Posted at Nginx Forum:

On Wed, Jan 19, 2011 at 5:52 AM, Antnio P. P. Almeida [email protected]
wrote:

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 :slight_smile:

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 :wink:

See GitHub - openresty/lua-nginx-module: Embed the Power of Lua into NGINX HTTP servers for more details.

Cheers,
-agentzh

OK finally figured it out I think.

Seems it may be to do with the scope of the user set variables (not
sure) but after moving adding proxy_no_cache and proxy_cache_bypass to
the same location instead of the centrally called ones, It seems to be
working as expected.

The hint was in agentzh’s original post

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 …
}

Posted at Nginx Forum: