Serve content from a site directory, if not found then use a different root

Hello all,

I am trying Caddy with a very simple personal website, made with plain HTML.
The idea is to migrate to caddy, and then migrate to a Hugo-based site.

I wonder if its possible to use rewrite (or another directive) to have the existing HTML pages to be rendered if they exist, but if not found, continue looking on a different path, /new for instance.

Not sure if I am clear, the idea is that anyone with an existing link

http://www.site.com/personal.html

will be served with the corresponding “legacy” ./personal.html, but if that does not exists then try /new/personal.html.

That would allow a partial migration to new content, without breaking any existing links.

Does it make sense?

Thanks for the patience,
///Pablo

I typically recommend redirects for this kind of thing so that clients can update their links to the new locations. But, to do what you want isn’t too hard:

rewrite {
    to {uri} /new{uri}
}

I think. This is untested, but what this should do is try the original URI first (which starts with a /), then the “new” path. Rewrites are internal though, so clients may continue requesting the old path forever; they’ll never know it changed. But for temporary migrations, it may be what you want.

Thanks, Matt,

I used you suggestion and actually was able to do what I wanted: Have the old site served from “/old/” source directory, and create the new site on the / path while I migrate things.

I absolutely agree about the benefits for redirection, and will be redirecting each old section to the new one, whenever that new section is ready. The idea is to stay 100% sure that anything I am not covering on the new site will be still served.

One thing to point, is that this “fallback” implied on the rewrite directive was not immediately clear to me, and maybe that fact can be pointed out on the Caddfile docs? I re-read it and still find no reference of the logic for “continuing to try” if the rewrite fails.

Thanks for your support!
By the way, Caddy rocks!

1 Like

Hi @pdinoto,

I think the behaviour you’re referring to is indeed documented at https://caddyserver.com/docs/rewrite:

destinations… is one or more space-separated paths to rewrite to, with support for request placeholders as well as numbered regular expression captures such as {1}, {2}, etc. Rewrite will check each destination in order and rewrite to the first destination that exists. Each one is checked as a file or, if ends with /, as a directory. The last destination will act as default if no other destination exists.

Maybe it could be clearer, though - do you have any suggestions on how the documentation could be improved?

Well, now that I re-re-read the section you are right, it is clearly stated.
Thanks!

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