Auto-try parent paths in file_server

Hey :slight_smile:

I would like to configure a file_server in case of an error to try moving up parent directories until one is found that matches, trying with and without trailing slashes, for example:

example.com/test/hi/

should try:

example.com/test/hi/
example.com/test/hi
example.com/test/hi.html
example.com/test
example.com/test.html
example.com/

Trying the directory itself is not as important, but the ability to try without a trailing slash if provided matters.

This is what I have so far:

try_files {path}.html {path}
file_server

handle_errors {
  redir * /
  file_server
}

But it only works for few of the aforementioned cases.

What about redir * ../{file} ?

1 Like

decent hint, but three issues:

  • does not try without trailing slash
  • redirects /test/hi to /hi rather than /test
  • when arriving at /test, it redirects infinitely

Oh I see, you want to trim the file component each time, not keep it.

So then just redir * ../ should do it Iā€™d think?

1 Like

Ah I tried that but was missing some extra hoops, this fixed it, maybe it can be simplified? And it does not try the very first variant, it just trims a trailing slash, but that seems fine for my use-case:

@trail path_regexp trail ^(.*)/$
rewrite @trail {re.trail.1}

root * /srv
try_files {path}.html {path}
file_server

handle_errors {
  redir * ..
}
1 Like

Cool, looks good to me.

On the latest Caddy version (2.8+) you can use root /srv directly now :slight_smile:

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.