You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx中如何根据响应码配置Cache-Control响应头

Nginx 根据响应状态码设置 Cache-Control 头的配置方案

对应变量说明

Nginx 里没有 $response_cache_control 这个内置变量,但有**$upstream_http_cache_control**——它可以获取上游服务器返回的响应头中的 Cache-Control 值,完全能满足你“保留原响应Cache-Control值”的需求。

修正后的 map 配置

你提供的配置存在语法错误(default 行末尾多了一个双引号),修正后的完整代码如下:

map $status $bb2_cache_control_header {
    301    "no-cache, no-store, must-revalidate";
    default $upstream_http_cache_control;
}

应用变量到响应头

配置好 map 后,需要把变量绑定到响应头,分两种场景处理:

  • 若你的 Nginx 安装了 headers_more 模块(推荐,能直接替换原有响应头):
    more_set_headers "Cache-Control: $bb2_cache_control_header";
    
  • 若无 headers_more 模块,使用原生 add_header,但要注意:上游返回的 Cache-Control 会和新设置的头重复,需先隐藏原有头再添加(要求 Nginx 1.17.9+ 版本):
    proxy_hide_header Cache-Control;
    add_header Cache-Control $bb2_cache_control_header always;
    
    加上 always 参数能确保301这类非2xx状态码下,新的Cache-Control头也能生效。

内容的提问来源于stack exchange,提问作者kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 22:45:30