I have a nginx proxy to a API server. The API sometimes sets the cache control header. If the API hasnt set the cache control I want nginx to override it.
How do I do that?
I think I want to do something like this, but it doesnt work.
location /api {
if ($sent_http_cache_control !~* "max-age=90") {
add_header Cache-Control no-store;
add_header Cache-Control no-cache;
add_header Cache-Control private;
}
proxy_pass $apiPath;
}
You cannot use
if
here, becauseif
, being a part of the rewrite module, is evaluated at a very early stage of the request processing, way beforeproxy_pass
is called and the header is returned from the upstream server.One way to solve your problem is to use
map
directive. Variables defined withmap
are evaluated only when they are used, which is exactly what you need here. Sketchily, your configuration in this case would look like this:Awswer from Ivan Tsirulev is correct but you don't have to use regex.
Nginx uses the first parameter of
map
as default value automatically so you don't have to add that either.