Nginx: location, try_files, rewrite: Find pattern match in subfolder, else move on

nginx

I'd like for Nginx to do the following:

If the uri matches the pattern:

http://mysite.com/$string/

and $string is not 'KB', and not 'images', look for $string.html in a specific subfolder. If $string.html exists in the subfolder, return it. If it does not exist, move on to the next matching location.

$string = {any letters, numbers, or dash}

For example, if the user requests:

http://mysite.com/test/

It should look for a file called:

 /webroot/www/myfolder/test.html

I've tried variations of:

location ~ /[a-zA-Z0-9\-]+/
{
   try_files /myfolder/$uri.html @Nowhere;
}

But:

  1. It doesn't seem to find the file even when it does exist, and
  2. If it fails (which is always right now), it wants to jump to the @nowhere location, rather than moving on and trying to find another location that matches.

I'd like for it to consider the current location "not a match" if the file doesn't exist.

Best Answer

I think you can try this:

location ~* ^/(KB|images)/$ {
   #rule for KB or images goes here
}

location ~* ^/([a-zA-Z0-9\-]+)/$ {
   root /webroot/www/myfolder/;
   try_files $1.html @Nowhere;
}

location @Nowhere {
   #rule for @Nowhere goes here
}

For more, refer to: http://wiki.nginx.org/HttpCoreModule#location

Related Topic