How to serve SPA applications with Caddy v2

I would like to see how to configure Caddy v2 to serve a SPA application.
It’s a basic configuration for any SPA application, that is, the server should always serve the index.html if a particular path is not found.

I’m trying the rewrite directive as follows, but it’s not working.

:8383 {
  rewrite {
      regexp .*
      to {path} /
  }
  header /img/* Cache-Control max-age=31536000
  header /js/* Cache-Control max-age=31536000
  header /css/* Cache-Control max-age=31536000
  header /fonts/* Cache-Control max-age=31536000
  encode gzip
  root * /usr/share/caddy
  file_server
}

I have found the solution in the documentation. This is the correct solution:

:8383 {
  try_files {path} /
  header /img/* Cache-Control max-age=31536000
  header /js/* Cache-Control max-age=31536000
  header /css/* Cache-Control max-age=31536000
  header /fonts/* Cache-Control max-age=31536000
  encode gzip
  root * /usr/share/caddy
  file_server
}
2 Likes

To clarify, for anyone finding this from a search, the only relevant part is try_files {path} / (and of course file_server and root but those are standard for static files). Everything else is irrelevant to SPAs.

1 Like

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