single-page-applicationcaddycaddyfile

Caddyfile with multiple Single Page Applications


Let's say I have following file structure:

- Caddyfile
- files
  - app1
    - index.html
  - app2
    - index.html
  - app3
    - index.html

Where app1, app2 and app3 are Single Page Applications with clientside routing. I am using Caddy v2. I want to route /app1/* to app1 directory and likewise other two, falling back to respective index.html in case searched for file doesn't exist.

I think that for one app correct configuration is:

handle /app1/* {
  file_server {
    root ./files/app1
    try_files {path} /index.html 
  }
}

And that I can just repeat this once for each app. I want to know if it is possible to define this more succintly, since our company currently has 20-30 SPAs, for example with something like:

file_server {
    root ./files
    try_files {path} {Maybe something here?}/index.html 
}

Solution

  • I figured it out.

    @spa path_regexp spa ^(.*[\\\/])
    
    handle @spa {
        root * ./files
        try_files {path} {path}.html {path}/ {path}/index.html {re.spa.1}/index.html    
        file_server
    }
    

    Regex matches everything before last slash, so for example in /files/app1/clientroute matched is /files/app1/. Then we use this match in {re.spa.1}/index.html and so reroute to /files/app1/index.html.