【问题标题】:How to add headers in nginx only sometimes仅有时如何在 nginx 中添加标头
【发布时间】:2015-09-10 02:56:20
【问题描述】:

我有一个到 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;
}

【问题讨论】:

  • 您能否澄清一下,如果上游没有设置标头,或者如果它不包含max-age=90,您想覆盖标头?
  • 谢谢@IvanTsirulev。理想情况下,如果它不存在。但我试图匹配上游在该示例中设置的值。

标签: nginx cache-control


【解决方案1】:

您不能在此处使用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;
    }
    ...
}

【讨论】:

  • 你先生是个传奇!谢谢。
【解决方案2】:

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

【讨论】:

猜你喜欢
  • 2015-06-10
  • 2017-10-08
  • 1970-01-01
  • 1970-01-01
  • 2012-11-15
  • 2021-03-09
  • 2016-10-28
  • 1970-01-01
  • 2013-01-08
相关资源
最近更新 更多