如果后端关闭,nginx 使用代理缓存

swe*_*web 11 nginx failover proxy cache

如果后端服务器关闭,我需要 nginx 代理使用缓存:

这是我的配置。但似乎是 nginx 使用缓存而不检查后端服务器。

http {

  # ...

  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_cache_path /tmp/nginx levels=1:2 keys_zone=tmpzone:10m inactive=60m;
  proxy_cache_key "$scheme$request_method$host$request_uri";


  server {
    server_name _;

    location / {
      proxy_connect_timeout 5s;
      proxy_read_timeout 5s;
      proxy_cache tmpzone;
      proxy_cache_valid      200 304 1d;
      proxy_cache_use_stale  error timeout invalid_header updating http_500 http_502 http_503 http_504;
      proxy_set_header X-Real-IP  $remote_addr;
      proxy_set_header X-Forwarded-For $remote_addr;
      proxy_set_header Host 'www.example.com';
      proxy_pass http://www.example.com;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

问题是,如果后端服务器已启动,我如何绕过代理缓存?当后端服务器启动时,我的代理服务器根本不使用缓存。

Fre*_*edi 8

似乎是这个的重复:

/sf/ask/1172939001/

总之,使用proxy_cache_use_stale

作为更新,我对此进行了测试,效果很好。我在我的工作站中进行了测试(为了完整性):

Fedora 23 nginx 1.8.1 配置为 ssl 终结器 + 缓存 + 反向代理 Apache 2.4.18 配置为监听 80 端口

使用 apache 作为上游,只提供一个静态文件,我做了这个测试:

  1. Apache up,nginx up,将浏览器指向 nginx 提供的反向代理 URL,我看到了来自 Apache 的代理内容。此时 nginx 将其保存在缓存中。
  2. 停止阿帕奇
  3. 连接到 nginx 我看到了 Apache 之前提供的缓存文件。

我使用的 nginx 配置是(只有有趣的部分):

nginx.conf :

http {
[...]
location
    proxy_cache_path        /var/lib/nginx/tmp/proxy/ levels=1:2 keys_zone=STATIC:10m inactive=24h max_size=1g;
    include /etc/nginx/conf.d/*.conf;
}
Run Code Online (Sandbox Code Playgroud)

/etc/nginx/conf.d/local.conf :

upstream localhost {
    server 127.0.0.1:80;
[...]
}


server {
    listen       127.0.0.1:443 ssl;

[...]

    location /be/ {
        proxy_pass              http://localhost;
        proxy_cache             STATIC;
        proxy_cache_valid       200 1d;
        proxy_cache_use_stale   error;
}
Run Code Online (Sandbox Code Playgroud)