title: Nginx bypass cache if upstream is up and use cache if down
body: <p>To bypass cache if upstream is up (max-age 1) and use cache if down (proxy_cache_use_stale) I created following config:</p>
  
  <pre><code>proxy_cache_path   /app/cache/ui levels=1:2 keys_zone=ui:10m max_size=1g inactive=30d;
  server {
      ...
      location /app/ui/config.json {
          proxy_cache ui;
          proxy_cache_valid 1d;
          proxy_ignore_headers Expires;           
          proxy_hide_header Expires;
          proxy_hide_header Cache-Control;
          add_header Cache-Control "max-age=1, public";
          proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
          add_header X-Cache-Status $upstream_cache_status;
          add_header X-Cache-Date $upstream_http_date;
          proxy_pass http://app/config.json;
      }
  }
  </code></pre>
  
  <p>But cache is not used when upstream is down and client only gets 504 Gateway Timeout. I've already read following articles:</p>
  
  <p><a href="https://nginx.org/ru/docs/http/ngx_http_proxy_module.html#proxy_cache_use_stale" rel="noreferrer">https://nginx.org/ru/docs/http/ngx_http_proxy_module.html#proxy_cache_use_stale</a></p>
  
  <p><a href="https://stackoverflow.com/questions/16756271/how-to-configure-nginx-to-serve-cached-content-only-when-backend-is-down-5xx-re">How to configure NginX to serve Cached Content only when Backend is down (5xx Resp. Codes)?</a></p>
  
  <p><a href="https://serverfault.com/questions/752838/nginx-use-proxy-cache-if-backend-is-down">https://serverfault.com/questions/752838/nginx-use-proxy-cache-if-backend-is-down</a></p>
  
  <p>And It does not work as I expect. Any help is appreciated.</p>