You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx能否无条件缓存代理的响应?

问题描述

我需要对一台既不返回Expires头也不返回Cache-Control头的上游服务器实现无条件缓存,且我无法管理这台上游服务器。

当前使用的Nginx配置如下:

proxy_cache_path /tmp/nginx keys_zone=motus_cache:2m max_size=1g
                 inactive=60m use_temp_path=off;

server {
        listen 8000 default_server;
        listen [::]:8000 default_server;
        server_name _;                  

        location / {                    
                proxy_cache motus_cache;     
                proxy_buffering on;
                proxy_pass https://motus.org;    
                proxy_ssl_name "motus.org";
                proxy_ssl_server_name on;
                proxy_ignore_headers "Set-Cookie" "Expires" "Cache-Control";                   
                proxy_hide_header Set-Cookie;            
                proxy_hide_header X-Powered-By;
        }

}

示例请求

curl -o /dev/null 'http://localhost:8000/data/binary/tagVisits'

(该请求耗时约7秒)

上游服务器响应头

< HTTP/1.1 200 200                                                                                  
< Content-Type: application/octet-stream                                                            
< Server: Microsoft-IIS/8.5                                                                          
< Set-Cookie: JSESSIONID=FE61DA4E7BD4996C09FB2B6D5E40D8CF; Path=/; Secure; HttpOnly                 
< X-Powered-By: ASP.NET
< Date: Mon, 10 Oct 2022 20:12:18 GMT
< Content-Length: 2779146 
解决方案

当前配置里,虽然已经通过proxy_ignore_headers忽略了上游的Expires、Cache-Control和Set-Cookie头,但Nginx默认不会缓存没有明确有效期的响应。要实现无条件缓存,必须添加proxy_cache_valid指令强制设置缓存时长。

修改后的location块配置如下:

location / {                    
        proxy_cache motus_cache;     
        proxy_buffering on;
        proxy_pass https://motus.org;    
        proxy_ssl_name "motus.org";
        proxy_ssl_server_name on;
        proxy_ignore_headers "Set-Cookie" "Expires" "Cache-Control";                   
        proxy_hide_header Set-Cookie;            
        proxy_hide_header X-Powered-By;
        # 强制将所有200状态码的响应缓存60分钟
        proxy_cache_valid 200 60m;
        # 如需缓存其他状态码,可添加额外规则,例如:
        # proxy_cache_valid 404 10m;
}

关键说明

  • proxy_cache_valid 200 60m:指定HTTP 200状态的响应缓存60分钟,可根据需求调整时长(如1h代表1小时,1d代表1天)。
  • 上游返回的Set-Cookie头已通过proxy_ignore_headers忽略,避免Nginx因Cookie不缓存响应,这一步配置正确。
  • proxy_cache_path中的inactive=60m表示缓存内容60分钟未被访问就会被清理,该配置可保留。

修改配置后重启Nginx,首次请求仍会耗时约7秒,但后续请求会直接读取缓存,耗时大幅降低。

内容的提问来源于stack exchange,提问作者TvE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 05:15:28