With a few features from the latest release of Caddy, especially {labelN} placeholders, this gets much easier!
http://*.example.com, https://*.example.com {
redir www.{label1}.example.com
tls {
...
}
}
# It's important that www.example.com exists
# as another site label so that it doesn't get
# redirected to www.www.example.com...
www.example.com {
...
}
It’s worth noting that http://*.example.com, https://*.example.com can be reduced to *.example.com, if you don’t mind a double-redirect in your case and if you prefer simplicity. (HTTP->HTTPS is automatic, and then the www redirect is the second one). Whitestrake’s example is optimized for just one redirect.
Yep, that definitely shouldn’t be happening. Can you run curl -IL http://example.com/ and post the output so we can see exactly how Caddy is responding?
That’s a relative link; it’s telling the browser, in that instance, to go to https://example.com/www.example.com. That runs into the redirect statement again, hence the infinite redirect.
Off the top of my head, I don’t think it should be assuming a leading slash… But you should be redirecting to HTTPS anyway; fix this by prepending all your redir hosts with https://, e.g. redir https://www.{label1}.example.com.
Secondly… Location: /www..example.com. Ignoring the leading slash, we’ve got an entire URL element missing. It should be filled in with the result of {label1}, e.g. sub1, but it has been given the empty result instead. It should be impossible for this to happen - {label1} should always have a valid result, because every host in a Caddyfile has at least one element.
So just to check, can you run caddy -version and make sure you’re on the latest release I mentioned in the second post, version 0.10.12? Being on version 0.10.11 or earlier would result in these placeholders being empty. If you are indeed on version 0.10.12, we might have to look further into how this happened, possibly as a bug of some kind.