Caddy V2 http->https redirect

I followed the helpful guide at Hugo's There - Flying with Hugo and Caddy · Fly to setup Caddy V2 to serve a static site with Fly, but that guide doesn’t cover http->https redirects (which aren’t automatically turned on when you switch to your own domain name instead of fly.dev). The solution is simple, but I had a bear of a time figuring it out so I thought I’d log it here for anyone else trying to do the same thing. Here’s my updated Caddyfile:

{
	auto_https off # Fly manages certs and terminates SSL for us
}

http://<put yoursite.com here> {

	# Redirect insecure requests (as identified by the trusted X-Forwarded-Proto
	# header from Fly) to https
	@insecure {
		header X-Forwarded-Proto http
	}
	redir @insecure https://{host}{uri} permanent

	root * /usr/share/caddy
	file_server
}
2 Likes