如果响应 NGINX 中没有 Cache-Control 标头,如何缓存内容
Posted
技术标签:
【中文标题】如果响应 NGINX 中没有 Cache-Control 标头,如何缓存内容【英文标题】:How to cache content if there is no Cache-Control header in the response NGINX 【发布时间】:2021-11-10 19:17:42 【问题描述】:我有一个安装了 nginx 的 Ubuntu 实例,并将其配置为一台主机上的转发代理,用于我在另一台主机上的应用程序。 我的应用程序正在向 NGINX 发出 GET 请求,NGINX 正在向外部服务器发出另一个 GET 请求(请求中指定了此服务器的 URL)并将响应返回给应用程序。 NGINX 应该缓存来自外部服务器的响应。 我需要尊重响应中的 Cache-Control 标头(只要此标头说明,缓存响应)但是!当响应中没有 Cache-Control 头时,必须缓存 12h,如何实现呢? 谢谢! :)
这是我的实际配置:
proxy_cache_path /tmp/nginx_cache levels=1:2 keys_zone=my_cache:100m max_size=2m inactive=12h use_temp_path=off;
location ~*
resolver xx.xx.x.xxx;
proxy_cache my_cache;
add_header X-Cache-Status $upstream_cache_status;
if ($http_x_example_use_https = '1')
proxy_pass https://$host;
if ($http_x_example_use_https = '0')
proxy_pass http://$host;
proxy_redirect off;
proxy_connect_timeout 4;
proxy_send_timeout 4;
proxy_read_timeout 4;
send_timeout 4;
proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
proxy_cache_lock on;
PS 有什么想法可以改进这个配置或改变一些东西吗? :)
【问题讨论】:
【参考方案1】:我想我已经解决了我的问题:
proxy_cache_valid 200 12h;
并且当 Cache-Control 标头存在时,它不应该被上面的这个指令覆盖。
NGINX 文档:
缓存的参数也可以直接在响应头中设置。这比使用指令设置缓存时间具有更高的优先级。 如果头部不包含“X-Accel-Expires”字段,可以在头部字段“Expires”或“Cache-Control”中设置缓存参数。
【讨论】:
以上是关于如果响应 NGINX 中没有 Cache-Control 标头,如何缓存内容的主要内容,如果未能解决你的问题,请参考以下文章