如果后端处于closures状态,nginx使用代理caching

如果后端服务器closures,我需要nginx代理使用caching

这是我的configuration。 但似乎是nginx使用caching没有检查后端服务器。

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; } } } 

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

似乎这是一个重复的:

https://stackoverflow.com/questions/16756271/how-to-configure-nginx-to-serve-cached-content-only-when-backend-is-down-5xx-re

总之,使用proxy_cache_use_stale

作为更新,我testing了这个,它工作正常。 我在我的工作站做了testing(为了完整性):

Fedora 23 nginx 1.8.1configuration为ssl终结器+caching+反向代理Apache 2.4.18configuration为侦听端口80

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

  1. Apache up,nginx up,将浏览器指向由nginx提供的反向代理URL,我看到来自Apache的代理内容。 在这一点上nginx保持这个caching。
  2. 停止了Apache
  3. 连接到nginx我看到由Apache之前服务的caching文件。

我使用的nginxconfiguration(只有有趣的部分):

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; } 

/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; } 

将proxy_intercept_errors和代理500使用到启用了caching的服务器。