如何有时只在nginx中添加标题

时间:2015-06-24 04:17:14

标签: nginx cache-control

我有一个API服务器的nginx代理。 API有时会设置缓存控制标头。如果API没有设置缓存控制,我希望nginx覆盖它。

我该怎么做?

我想我想做这样的事情,但它不起作用。

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;
}

2 个答案:

答案 0 :(得分:11)

你不能在这里使用if,因为作为重写模块的一部分的if在请求处理的早期阶段进行评估,在调用proxy_pass之前进行评估,标头从上游服务器返回。

解决问题的一种方法是使用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;
    }
    ...
}

答案 1 :(得分:6)

来自Ivan Tsirulev的Awswer是正确的,但您不必使用正则表达式。

Nginx自动使用map的第一个参数作为默认值,因此您不必添加它。

# Get value from Http-Cache-Control header but override it when it's 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;
    }
    ...
}