Proxy_cache only if custom header is set by upstream

Hi,

i know how to prevent caching if custom headers are set by upstream
with proxy_cache_bypass and proxy_no_cache.

This time i’d like to do the opposite, i want the response to be cached
only if a custom header is present.

I tried something like:

set $nocache 1;

proxy_no_cache $nocache;

if ($upstream_http_myheader = 1) {

set $nocache 0;

}

But this doesn’t work. Any ideas or am i missing something?

cheers

Thomas Lohner

Posted at Nginx Forum:

Hello!

On Tue, May 15, 2012 at 11:42:12AM -0400, ThomasLohner wrote:

set $nocache 1;

But this doesn’t work.

And it’s not expected to, as “if” directives, as well as other
rewrite module directives, are executed before request goes to
upstream and hence $upstream_http_myheader isn’t known.

Any ideas or am i missing something?

Use map instead, Module ngx_http_map_module.

Something like this should work:

map $upstream_http_myheader $nocache {
    default 0;
    1       1;
}

proxy_no_cache $nocache;

Maxim D.

On Tuesday 15 May 2012 19:42:12 ThomasLohner wrote:

set $nocache 1;

But this doesn’t work. Any ideas or am i missing something?

The rewrite module works before the request is passed to upstream, so
upstream
variables is empty on rewrite stage.

You can use the map directive which is evaluated at the time of use.

wbr, Valentin V. Bartenev

Yeah! Thanks, maybe you should add to the wiki, that “if” is executed
before proxy_pass :wink:

Anyways, thank you very much for this helpful answer, it works this
way.

obviously the map has to be the other way around, so if anyone finds
this… the correct way for caching only if upstream sets a custom header
is:

map $upstream_http_myheader $nocache {
default 1;
1 0;
}

proxy_no_cache $nocache;

Posted at Nginx Forum: