为了在上游启动时绕过缓存(max-age 1)并在关闭时使用缓存(proxy_cache_use_stale),我创建了以下配置:
proxy_cache_path /app/cache/ui levels=1:2 keys_zone=ui:10m max_size=1g inactive=30d;
server {
...
location /app/ui/config.json {
proxy_cache ui;
proxy_cache_valid 1d;
proxy_ignore_headers Expires;
proxy_hide_header Expires;
proxy_hide_header Cache-Control;
add_header Cache-Control "max-age=1, public";
proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
add_header X-Cache-Status $upstream_cache_status;
add_header X-Cache-Date $upstream_http_date;
proxy_pass http://app/config.json;
}
}
但是当上游关闭并且客户端仅获得 504 Gateway Timeout 时,不使用缓存。我已经阅读了以下文章:
https://nginx.org/ru/docs/http/ngx_http_proxy_module.html#proxy_cache_use_stale
如何配置 NginX 仅在后端关闭时提供缓存内容(5xx 响应代码)?
https://serverfault.com/questions/752838/nginx-use-proxy-cache-if-backend-is-down
它不像我预期的那样工作。任何帮助表示赞赏。