Serving pages in a subfolder as the root

I have a site structure that has static pages and resources in a subdirectory, like static/index.html, static/logo.png, static/style.css and I want to serve these contents at the root of my site, like http://example.com/ will show static/index.html and so on.

I thought a rewrite would do it, but apparently I don’t know anything about rewrites.

rewrite / /static

Doesn’t rewrite anything, instead it redirects from / to /static. If I visit http://example.com/ it will redirect me to http://example.com/static/ and then the HTML from static/index.html will be served. What is happening?

I’m also very sad now because its issuing 301 redirects, which get cached by the browser and will cause lots of issues in the future.

Ok, I finally solved it.

Apparently

rewrite {
  to static/{path}
}

is the most simple and only correct way to do this. I’m still not sure why this works and not the previous example (or the other thousand things I’ve tried before and have since forgotten).

You could also just set another root if you do not want any other files to be accessible.

root /home/jake/public_html/static
2 Likes

To clarify this - rewrite sets the rewritten URI to whatever you specify.

If you’re rewriting to /static, Caddy is going to pretend like the client directly requested /static, and nothing else.

What you’re trying to achieve is prepending their request with the static folder. For a request to /foo/bar/img.png, you want to serve /static/foo/bar/image.png. The {path} placeholder gives you their original request, so you actually want to rewrite to /static{path}.

Technically your rewrite, static/{path}, will result in a double slash (i.e. static//[whatever]) because {path} includes the leading slash. Caddy will sanitize that before trying to actually use it, though, so it shouldn’t cause any problems.

And, as stated, your simplest solution is actually to set static as your web root.

1 Like

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