How to add headers in nginx only sometimes

I have a nginx proxy for an API server. The API sometimes sets a cache control header. If the API has not set cache control, I want nginx to override it.

How to do it?

I think I want to do something similar, but it does not 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;
}
+4
source share
2 answers

You cannot use here if, because if, being part of the rewrite module, it is evaluated at an early stage of the request processing before being proxy_passcalled, and the header is returned from the upstream server.

- map. , map, , , , . , :

# When the $custom_cache_control variable is being addressed
# look up the value of the Cache-Control header held in
# the $upstream_http_cache_control variable
map $upstream_http_cache_control $custom_cache_control {

    # Set the $custom_cache_control variable with the original
    # response header from the upstream server if it consists
    # of at least one character (. is a regular expression)
    "~."          $upstream_http_cache_control;

    # Otherwise set it with this value
    default       "no-store, no-cache, private";
}

server {
    ...
    location /api {
        proxy_pass $apiPath;

        # Prevent sending the original response header to the client
        # in order to avoid unnecessary duplication
        proxy_hide_header Cache-Control;

        # Evaluate and send the right header
        add_header Cache-Control $custom_cache_control;
    }
    ...
}
+7

, .

Nginx map , .

# Get value from Http-Cache-Control header but override it when it empty
map $upstream_http_cache_control $custom_cache_control {
    '' "no-store, no-cache, private";
}

server {
    ...
    location /api {
        # Use the value from map
        add_header Cache-Control $custom_cache_control;
    }
    ...
}
+3

All Articles