需在http块定义含$upstream_cache_status的log_format,并在启用proxy_cache的location中配置access_log;配合add_header可实时验证,六种状态对应不同缓存行为。

要在 Nginx 日志中记录缓存命中状态,关键是在 log_format 里显式加入 $upstream_cache_status 变量,并确保它在对应 location 中真正生效。
必须在 http 块定义日志格式
该变量只在启用 proxy_cache 的代理请求中有效,所以日志格式要定义在全局 http 块内,不能只写在 server 或 location 里:
- 在
http块中添加:log_format cache_log '$remote_addr [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" $upstream_cache_status $request_time $upstream_response_time'; - 注意:$upstream_cache_status 位置可自由调整,但不要漏掉;若值为空或“-”,说明当前请求未走 proxy_pass 或缓存未启用
在目标 location 中启用该日志格式
仅定义格式不够,还必须在具体代理路径的 location 块中调用 access_log:
- 例如针对 API 接口:
location /api/ {<br> proxy_pass http://backend;<br> proxy_cache my_cache;<br> access_log /var/log/nginx/api_cache.log cache_log;<br>} - 避免在纯静态文件 location(如 root + try_files)中使用该变量——它不生效,会输出“-”
配合响应头便于单次验证
光看日志不够直观,建议同步加一个调试响应头:
- 在相同 location 中添加:
add_header X-Cache-Status $upstream_cache_status always; - 用
curl -I https://example.com/api/data就能立刻看到返回头中的状态,比如X-Cache-Status: HIT - 这个头对前端或测试工具排查单次行为特别有用
统计时注意六种状态的真实含义
日志里可能出现的值不止 HIT 和 MISS,每种都代表不同缓存逻辑:
- HIT:缓存新鲜,直接返回,是理想状态
- MISS:首次访问或 key 不匹配,需回源
- EXPIRED:缓存存在但过期,已发条件请求验证
-
STALE:返回了过期内容(因配置了
proxy_cache_use_stale) -
BYPASS:被
proxy_cache_bypass规则跳过 - UPDATING:缓存正在后台更新,返回旧内容











