首页 > 解决方案 > 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使用 缓存条目,但仅在上游服务器关闭时才使用缓存的条目?

标签: nginxcaching

解决方案


我看到两种可能性:

  1. NGINX 尊重来自上游服务器的标头。因此,如果上游发送Expires,尽管Cache-Control: no-store在您修改 NGINX 的标头之后,它们会变成Expires: ... Cache-Control: stale-if-error并等待

    至少只要缓存有效

  2. proxy_cache_valid可能有同样的效果

所以你需要

  1. proxy_cache_valid要么为for设置一些小的值location /somewhere
  2. 或/Expires如果存在则删除
  3. 或/和添加max-age=0Cache-Control

推荐阅读