在 nginx 中配置 proxy_cache_use_stale 以处理失效,核心在于启用缓存并设置该指令为允许返回过期或错误时的旧数据。你需要确保 proxy_cache_path 已正确定义,并在 location 块中开启 proxy_cache,同时指定 proxy_cache_use_stale 的触发条件(如 updating、error 等)。这样当后端服务不可用或响应缓慢时,nginx 会直接返回缓存中的 stale 数据,而不是直接报错。

如何配置 proxy_cache_use_stale 的基础环境
要使用 proxy_cache_use_stale,必须先建立缓存存储路径并激活缓存功能。这涉及到 proxy_cache_path 和 proxy_cache 两个关键指令。没有这两步,后续的 stale 配置将无效。

http {
# 1. 定义缓存路径和参数
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m;
server {
listen 80;
server_name example.com;
location /api/ {
# 2. 激活缓存
proxy_cache my_cache;
# 3. 设置 stale 策略:当后端更新缓存时,或后端报错时,返回旧缓存
proxy_cache_use_stale updating error timeout http_500 http_502 http_503 http_504;
# 4. 设置后端地址
proxy_pass http://backend_servers;
}
}
}
proxy_cache_use_stale 的具体触发条件有哪些
proxy_cache_use_stale 支持多种条件,常见的是 updating(后台重新获取)和 error(后端连接失败)。这些条件决定了在什么情况下 Nginx 会忽略缓存过期时间而提供旧数据。

# 在 location 块中细化条件
location /api/ {
proxy_cache my_cache;
# 仅在后端超时或 HTTP 5xx 错误时返回 stale
proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
# 可选:设置 stale-while-revalidate 时间,允许在后台刷新
proxy_cache_background_update on;
proxy_pass http://backend_servers;
}
当 proxy_cache_use_stale 与 proxy_cache_valid 冲突时如何处理
如果设置了 proxy_cache_valid 但缓存未命中或过期,且未配置 proxy_cache_use_stale,请求将直接转发到后端。若后端也失败,则返回错误。配置 proxy_cache_use_stale 可以覆盖这一行为,强制返回旧数据。需确保 proxy_cache_valid 的时间小于缓存文件的实际存活时间,否则 stale 可能永远不会被触发。











