如何配置Nginx仅缓存返回文件的API端点?
解决方案
修正后的Nginx配置
server { listen 8081; proxy_cache wado_cache; # 默认所有请求不缓存 proxy_cache_valid any 0; proxy_ignore_headers "Cache-Control" "Expires"; location / { add_header hd_content_disposition "$upstream_http_content_disposition"; proxy_pass http://192.168.1.2:8080/; proxy_hide_header Cache-Control; add_header Nginx-Cache-Status "$upstream_cache_status"; # 仅当上游返回content-disposition头时启用缓存 set $cache_enable 0; if ($upstream_http_content_disposition) { set $cache_enable 1; } # 缓存带content-disposition的200响应60分钟 proxy_cache_valid 200 $cache_enable 60m; # 非文件请求绕过缓存且不写入缓存 proxy_cache_bypass $cache_enable; proxy_no_cache $cache_enable; } }
配置说明
- 默认禁用缓存:通过
proxy_cache_valid any 0;设置默认不缓存任何响应,避免JSON请求被默认缓存。 - 动态缓存控制:用
$cache_enable变量判断上游是否返回content-disposition头,仅当存在该头时才启用60分钟缓存。 - 修正缓存逻辑:
- 原配置中
proxy_cache_bypass $upstream_http_content_disposition逻辑完全错误,它表示只要上游返回该头就绕过缓存,和需求相反。 - 修正后,
proxy_cache_bypass $cache_enable和proxy_no_cache $cache_enable确保:带content-disposition的请求会被缓存,JSON请求直接走上游且不写入缓存。
- 原配置中
内容的提问来源于stack exchange,提问作者Tuling Smith
相关产品推荐
相关产品推荐

