I don’t believe that exact behaviour can be configured per the HTTP Caddyfile spec, emphasis mine:
* can be used in a hostname. A wildcard must take the place of an entire domain label:
*.example.com is valid but
foo*.example.com is not. Hostnames may have more than one wildcard label, but they must be the left-most labels.
The closest configuration I can think of would be to use On-Demand TLS with an ask endpoint configured to respond affirmatively to hosts that begin with
www. and negatively otherwise. With the latest Caddy version (0.11.1), this will serve a self-signed certificate when the ask endpoint returns a negative response.
You won’t be able to define separate site definitions, but your
redir has an
if statement that ensures it only fires in the event of a
www hostname anyway, so you can simply stack the configuration you’ve given as an example into one site definition.