Not redirecting API from HTTP to HTTPS

Hi!

There was an excellent article about why you shouldn’t redirect API endpoints from HTTP to HTTPS: Your API Shouldn't Redirect HTTP to HTTPS

The perfect solutions would be to:

  • Close port 80. Tricky with ACME
  • Kill credentials that are used over plain HTTP. Lots of work

I’m interested in something that would provide benefits but would be easy to implement. We host our api on the same domain as the user facing site, but under /api/ .

How should I configure caddy so that HTTP → HTTPS redirect would work like it does by default, except for /api/ (or any other specific prefixes) that would return HTTP 426 or 403?

Hi @ptman,

What about the TLS-ALPN-01 and the DNS-01 challenge, neither of those require access to Port 80.

1 Like

You can add something like this to your Caddyfile (i.e. overriding the default HTTP->HTTPS redirect with your own config):

http://example.com {
	handle /api/* {
		error 403
	}
	handle {
		redir https://{host}{uri} 308
	}
}
3 Likes

Thank you, that seems to do the trick. And also keeps the redirect for non-API users. Does this interfere with automatic ACME?

Oh, another, related, question. If I use error "error-message" http-status, where does “error-message” end up? I didn’t find it in the error response to the client. How can I customize the error body?

Nope. Caddy inserts routes in front of all that to handle .well-known/acme-challenge/*

Take a look at the handle_errors directive:

1 Like

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