Search code examples
nginxstatic-files

Getting Nginx to serve static files from several sources


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

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

But what I want to do now is that if the static file doesn't exist in /tmp/static, Nginx looks for the file in /srv/www/site/static. I am not sure how to achieve that, I have tried a few things with try_files, but I don't know how to properly use it.


Solution

  • You can set your root to the common prefix of the two paths you want to use (in this case, it's /), then just specify the rest of the paths in the try_files args:

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

    It may seem disconcerting to use root / in a location, but the try_files will ensure that no files outside of /tmp/static or /srv/www/site/static will be served.