Search code examples
nginxuwsgihttp-caching

Enable UWSGI caching only when Cache-Control headers are set


I'd like to use Nginx to cache a Uwsgi app. The app sets the Cache-Control header for some requests. The Nginx-cache should only be enabled for those requests and respect the max-age condition.

So I'm trying to set uwsgi_no_cache 1 for requests where upstream doesn't set Cache-Control. And uwsgi_no_cache 0 for requests where upstream does set the Cache-Control header.

However, this does not work:

set $no_cache 1;
if ($sent_http_cache_control) {
    set $no_cache 0;
}
uwsgi_no_cache $no_cache;

The problem lies with $sent_http_cache_control, unfortunately it does not reflect the header set upstream.

Is there a way of only enabling caching in Nginx when Cache-Control is set upstream?


Solution

  • For headers returned by the upstream service you will need to use the $upstream_http_ prefix

    https://nginx.org/en/docs/http/ngx_http_upstream_module.html#var_upstream_http_

    So in your case it should be $upstream_http_cache_control