2

I'm currently trying to setup a nginx cache that should cache a location for a long time but if query parameters are present for only a few minutes.

So basically:

http://example.com/mypath -> long cache
http://example.com/mypath?param=1 -> short cache

My current config looks something like this:

location "~^(/mypath)"
{
        proxy_cache        example.com_my_cache_http;
        proxy_cache_valid 404 15m;
        ...
}

I can't use diffrent locations because locations can't match query parameters, I have tried using an if (I know it's bad practice)

if ($args ~ param) {
            proxy_cache        example.com_my_cache_http;
            proxy_cache_valid 404 15m;
} else {
            proxy_cache        example.com_my_cache_http;
            proxy_cache_valid 404 2d;
}

This results in:

Testing nginx configuration: nginx: [emerg] "proxy_cache" directive is not allowed here

I also tried using variables:

    set $time "1h";

    if ($args ~ param) {
        set $time "2m";
    }

    proxy_cache        example.com_my_cache_http;
    proxy_cache_valid 404 $time;

This results in:

Testing nginx configuration: nginx: [emerg] invalid time value "$time" 

I'm really running out of ideas any help or hint is appreciated.

2
  • 1
    You backend could send X-Accel-Expires header. Also, probably you just need to bypass cache?
    – Alexey Ten
    Dec 19 '14 at 11:59
  • Hi,bypassing is not an option as I still need a short cash to catch users that spam hit F5.
    – gries
    Dec 19 '14 at 12:23
1

My first thought would be to use a map.

map $arg_param $cache_valid_404 {
    ""      2d;
    1       15m;
}

Then you set:

proxy_cache_valid 404 $cache_valid_404;
3
  • where can I put the "map" ? I'm getting map directive not allowed here if I define it inside or outside of the location
    – gries
    Dec 19 '14 at 14:41
  • @gries map goes under http only. It should not be in any other place. Dec 19 '14 at 14:44
  • 1
    It doesn't work. 'nginx: [emerg] invalid time value "$cache_valid_404" in /path...'
    – dx7
    May 29 '17 at 19:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.