Getting Nginx to serve static files from multiple sources

I have a Nginx configuration that works fine and serves static files:

location /static/ { alias /tmp/static/; expires 30d; access_log off; } 

But now I want to say that if a static file does not exist in /tmp/static , Nginx looks for the file in /srv/www/site/static . I'm not sure how to achieve this, I tried several things with try_files , but I do not know how to use it correctly.

+7
source share
4 answers

You can set the root to the common prefix of the two paths that you want to use (in this case /), and then just specify the rest of the paths in the try_files files:

 location /static/ { root /; try_files /tmp$uri /srv/www/site$uri =404; expires 30d; access_log off; } 

You may not seem to like using root / in a location, but try_files ensures that files outside of / tmp / static or / srv / www / site / static will not be uploaded.

+8
source

The following should do the trick:

 location /static/ { expires 30d; access_log off; try_files tmp/static/$uri tmp/static/$uri/ tmp/static2/$uri tmp/static2/$uri/; } 

see http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files for documentation and examples of using try_files

+1
source

You can use the named location with "root" to handle a number of backup locations. Please note: you cannot use an "alias" inside a named location.

 location / { root /path/to/primary/html; try_files $uri $uri/ @fallback; } location @fallback { root /path/to/secondary/html; try_files $uri $uri/ =404; } 
+1
source

It looks like your needs will be served using the SlowFS Cache Module . It caches your static content in a temporary directory, which is supposedly stored on faster disks, and manages the backup for you.

-one
source

All Articles