Search code examples
nginxstatic-filesnginx-location

How to use try_files with 2 or more roots


I have looked hi and low and found no such implementation and am wondering if what I am trying is even possible. I have 3 relative paths that serve up static content:

Path1: /usr/local/www/style1/static/...
Path2: /usr/local/www/style2/static/...
Path3: /usr/local/www/style3/static/...

The 3 different roots are static unto themselves but the content from /static on down is only semi-static (might be a bit different depending on the exact file being served up and may exist in one path and not in another). For example

/static/css/custom.css
/static/css/form/button.css
/static/css/form/images/buttondisabled.png
/static/images/ui/buttons/add_item.png
/static/images/ui/menu/help.png

The following is what I would like to do. Which is basically, if "/static" content is requested I want to check the relative path associated with path1 and if not found there then check the relative path associated with path2 and if not found check the relative path associated with path3. This seems fairly simple but I have not found any examples that outline how this might be done. Could I set the 3 different roots up as variables perhaps:

path1root /usr/local/www/style1;
path2root /usr/local/www/style2;
path3root /usr/local/www/style3;

location /static
{
    try_files path1root/$uri path2root/$uri path3root/$uri (=404);
}

Or might that be done as follows since it is only needed for /static content:

location /static
{
    path1root /usr/local/www/style1;
    path2root /usr/local/www/style2;
    path3root /usr/local/www/style3;

    try_files path1root/$uri path2root/$uri path3root/$uri (=404);
}

Or can what I am attempting to do even be done at all ?? If I cannot do it with 3 roots could it be done with just 2 roots without defining one of them as an overall arching base root. If it is possible to do this and stay away from regular expressions that would be better -- but if that is needed then that is needed.


Solution

  • You could use a common root and try the three directories in the try_files statement:

    location /static {
        root /usr/local/www;
        try_files /style1$uri /style2$uri /style3$uri =404;
    }