加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 运营中心 > Nginx > 正文

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

发布时间:2020-12-13 21:23:39 所属栏目:Nginx 来源:网络整理
导读:我有一个API服务器的nginx代理. API有时会设置缓存控制标头.如果API没有设置缓存控件,我希望nginx覆盖它. 我怎么做? 我想我想做这样的事情,但它不起作用. location /api { if ($sent_http_cache_control !~* "max-age=90") { add_header Cache-Control no-s

我有一个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;
}
如果在这里,则不能使用,因为如果作为重写模块的一部分,在请求处理的早期阶段进行评估,则在调用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;
    }
    ...
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读