13

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.

Flavien
  • 7,497
  • 10
  • 45
  • 52

4 Answers4

11

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.

kolbyjack
  • 17,660
  • 5
  • 48
  • 35
  • For some reason, it doesn't work with $uri, when I use $request_uri it does, any idea why? – Flavien Sep 05 '12 at 22:35
  • 1
    $request_uri expands to the original, unprocessed uri path from the request line. It is unaffected by any internal redirects. $uri is the current uri path being processed, and it is changed by internal redirects. I'd guess that you're somehow internally redirecting and that's causing your issue. – kolbyjack Sep 05 '12 at 22:58
2

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 try_files use

cobaco
  • 10,224
  • 6
  • 36
  • 33
2

You can use a named location with "root" in order to process a series of fallback locations. Note that you cannot use "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;
}
sffc
  • 6,186
  • 3
  • 44
  • 68
0

It appears that your needs would be served by using the SlowFS Cache Module. It caches your static content in a temporary directory that is presumably stored on faster disks, and manages the fallback for you.

Mark Stosberg
  • 12,961
  • 6
  • 44
  • 49