nginx缓存:仅当上游服务器不可访问时,才返回缓存的页面(当指定了特定的Cache-Control标头时)

时间:2020-02-17 10:19:34

标签: nginx caching

我正在尝试为上游服务器(我不管理)设置缓存。大多数文件都可以被缓存(并且没有设置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缓存条目,但是仅在上游服务器关闭时才使用缓存的条目?

1 个答案:

答案 0 :(得分:1)

我看到两种可能性:

  1. NGINX尊重上游服务器的标头。因此,如果上游尽管发送了{{1}而发送了Expires,则在您为NGINX修改标头后,它们变成了Cache-Control: no-store并且它等待

    至少在缓存有效期间

  2. Expires: ... Cache-Control: stale-if-error可能具有相同的作用

所以你需要

  1. proxy_cache_valid的{​​{1}}设置一些较小的值
  2. 或/和删除proxy_cache_valid(如果存在)
  3. 或/并将location /somewhere添加到Expires