HSTS and proper redirects

I use just Cloudflare Pages with a static site deployed from Github Actions. The site works on a custom domain. I’d like to configure HSTS and redirects from secondary domain (e.g. example.com) to primary domain (e.g. www.example.com), so that:

  1. All requests to plain HTTP redirect the user to the same URL, just with HTTPS protocol. Reasoning: if we redirect to some other domain, HSTS will not be applied for this domain. (This seems to be the default behavior, but some other settings tend to break it, see below.)
  2. All HTTPS request to secondary domain redirect to primary domain (example.com vs. www.example.com) and return the HSTS header.
  3. All requests that aren’t redirected should return HSTS header. (Some edge-case exceptions, e.g. for .well-known, are acceptable.)

In other words, the redirect chains should be like this:

a. http://example.comhttps://example.com (with HSTS header) → https://www.example.com (with HSTS header)
b. http://www.example.comhttps://www.example.com (with HSTS header)

I think this is quite a common scenario, so I’d expect it to be easy, but it isn’t.

Redirect to primary domain

I was able to configure redirect from secondary domain to primary domain using Bulk Redirects. However, there is a drawback: They also seem to apply for both HTTPS and HTTP, which prevents HSTS from being applied to the secondary domain.

Maybe I can create a second site with just _redirects, but I believe there must be an easier way…


Via _headers file

I can set the HSTS header using _headers file. However, this isn’t applied to redirect. So, when user repeatedly enters http://example.com, it would always start with plain HTTP.

Via administration GUI (according to manuals)

There are multiple documents that mention configuring HSTS, but I haven’t succeeded with any.

  • HTTP Strict Transport Security (HSTS) · Cloudflare SSL/TLS docs – it doesn’t mention Cloudflare Pages, but it looks quite generic. OK, let’s choose the website on Pages. But there is none. However, it shows “Looking to register a new domain or build an application with Workers & Pages?”, so maybe it should work for Pages. But my site isn’t listed there.
  • On support page, I’ve tried to request a help for Cloudflare Pages. However, when I fill “Is your issue domain related?”, I can’t select the domain.
  • Someone else has asked a similar question, but they seem to be able to enable HSTS. I haven’t found the settings.