Enabling NGINX to forward static file request to origin server if the file is absent

Reinis Rozitis r at roze.lv
Wed Jun 21 08:48:34 UTC 2017


> Currently NGINX supports static file caching wherein if the file is 
> present
> in the location (derived from the config), then it will serve the client
> directly. Else it just intimates the client that the file is not present.

> There is no capability to forward the request to origin server, get the 
> the
> file, save it and serve it to the client AFAIK. I am not sure. Please
> correct me if I am wrong.


Hello,
I don't exactly understand how did you come to conclusion "There is no 
capability to forward the request to origin server, get the the file, save 
it and serve it"  .. the whole purpose of the nginx cache is to do exactly 
that.
And by using proxy_cache_lock and proxy_cache_use_stale you can finetune the 
behaviour.


Unless by "file is present in the location" you mean a file directory/tree 
not created by proxy_cache_path.

Even then it's possible to do something like this:

server {
..
        root                 /data/cache;

        location / {
            try_files $uri $uri/ @fetch;
        }

   location @fetch  {
          internal;
           proxy_pass           http://yourbackend;
           proxy_store          on;
    }
}


The proxy_store directive will physically save the file in the root.

The only drawback in this approach is that there is no request coalescing 
(the proxy_cache_lock has no effect on proxy_store).


rr 



More information about the nginx mailing list