nginx - nginx 缓存:仅当上游服务器不可访问时才返回缓存页面(当给出特定的 Cache-Control 标头时)
问题描述
我正在尝试为上游服务器(我不管理)设置缓存。大多数文件可以被缓存(并且没有Cache-Control
设置),那些工作正常。
但是,服务器上的某些位置是目录列表(并且有Cache-Control: no-store
)。我只想在服务器无法访问时缓存它们。
不幸的是,我最终会遇到以下情况之一:
- 在没有缓存这些列表的情况下(缓存中没有文件,标题总是显示缓存未命中)。如果服务器不可访问,则(显然)不返回目录列表
- 在这些列表被缓存的情况下,但它们之后永远不会更新(至少在缓存有效的情况下不会更新)。由于我想长时间缓存所有其他条目,因此目录列表很快就会过时。
我试图将标题修改为stale-if-error
,但这似乎也没有帮助。
map $http_cache_control $http_updated_cache_control {
no-store stale-if-error;
}
server {
...
location /somewhere {
sendfile on;
sendfile_max_chunk 10m;
tcp_nopush on;
proxy_cache keyzone;
# allow using stale requests in case of errors or when updating a file
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_revalidate on;
proxy_cache_background_update on;
# add header to indicate if caching works
add_header X-Cache-Status $upstream_cache_status;
proxy_cache_lock on;
proxy_read_timeout 900;
proxy_pass_header Server;
proxy_ignore_headers Set-Cookie;
# allow caching of non-cacheable entries only when the server is erroring
proxy_hide_header Cache-Control;
add_header Cache-Control $http_updated_cache_control;
# don't ignore the cache control header: some items (like directory listings) are marked as "don't cache")
#proxy_ignore_headers Cache-Control;
}
}
如何Cache-Control: no-store
使用 缓存条目,但仅在上游服务器关闭时才使用缓存的条目?
解决方案
我看到两种可能性:
- NGINX 尊重来自上游服务器的标头。因此,如果上游发送
Expires
,尽管Cache-Control: no-store
在您修改 NGINX 的标头之后,它们会变成Expires: ... Cache-Control: stale-if-error
并等待至少只要缓存有效
proxy_cache_valid
可能有同样的效果
所以你需要
proxy_cache_valid
要么为for设置一些小的值location /somewhere
- 或/
Expires
如果存在则删除 - 或/和添加
max-age=0
到Cache-Control
推荐阅读
- rundeck - 并行运行作业池,每个作业只执行一次
- javascript - 从 React 中的对象数组映射时,如何对每个单独的渲染元素进行操作?
- javascript - [...new set(array)] 如何在 javascript 中工作?
- php - 读取列表并将其存储为数组
- scala - Spark:错误的时间戳解析
- flutter - 在 Flutter 中使用线条和弧线绘制自定义形状
- xcode - 没有为 Xcode 11.7 团队找到具有 App Store Connect 访问权限的帐户
- javascript - Cloud Firestore 数据查询
- azure - Azure Blob 源错误:远程服务器返回错误:(400) 错误请求
- performance - 使用 EmEditor 优化列数据中的多元素排序/去重