I am trying to serve a jekyll blog on nginx. The files in the build directory should be reachable via the following routes:
- index.html -> /
- 1.0/
- index.html -> /1.0/
- foo/
a.html -> /1.0/foo/a/
b.html -> /1.0/foo/b/
c.html -> /1.0/foo/c/
- bar/
1.html -> /1.0/bar/1/
2.html -> /1.0/bar/2/
I tried to use the try_files directive in nginx but it always calls the fallback although the files are available. Here is the config:
location ~* ^(.+)/$ {
try_files $uri /$1/index.html /$1.html =404;
}
If I remove the 404 fallback it only works for the last value.
So my question is: What's the best way to configure nginx for serving static files like this?
If I remove the 404 fallback it only works for the last value.
This is because the last parameter of try_files
directive should be an HTTP error code or an URI to try if the file not found. In your case nginx assumes it is an URI.
Try this:
location ~ ^(?<path>/.*/)(?<file>[^/]+)/$ {
try_files $uri $path$file.html $uri/ =404;
}
If you want to serve http://example.com/1.0/foo/a
requests similar to http://example.com/1.0/foo/a/
, change regex to ^(?<path>/.*/)(?<file>[^/]+)/?$
.