Solution 1:

As noted on the HSTS preload list submission requirements:

  1. Redirect from HTTP to HTTPS on the same host, if you are listening on port 80.

You need to redirect to the same host (ie. HTTP_HOST), not simply to example.com first. You don't need to redirect to example.com if the user is requesting www.example.com directly. (The test will involve a request to example.com.) After that you can redirect to the canonical www subdomain if required.

I tried to add a redirect before the last line, this way:

RewriteRule ^(.*)$ https://example.com/$1 [R,L]

That would create a redirect loop, because the preceding RewriteCond directive only applies to the first RewriteRule, so the second RewriteRule would run unconditionally.

Try something like the following instead:

# HTTP to HTTPS redirect
RewriteCond %{SERVER_PORT} 80
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R,L]

# Canonical www redirect
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule (.*) https://www.%{HTTP_HOST}/$1 [R,L]

The HTTP_HOST server variable contains the value of the Host HTTP request header (ie. whatever host is being requested).

The 2nd redirect states... for all requests where the requested host does not start www. then prefix www. to the host. However, this might not be acceptable if you have multiple subdomains (that resolve to the same place) you want to keep separate, as they will naturally be redirected to the www subdomain.

Note that these are 302 (temporary) redirects. Change to 301 only when you are sure it's working OK.

And: are there any risks?

No risks. Yes, there are potentially two redirects whereas previously there might have only been one (which is arguably less efficient). But there are still only two redirects, which is perfectly OK for SEO. Besides, with HSTS, the user-agent will only ever experience the double redirect at most once.


RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

Aside: (Ignoring HSTS for the moment...) This wouldn't have been complete by itself, as it doesn't canonicalise a request for https://example.com/... (ie. HTTPS and domain apex).


Further reading:

  • My answer to a related question on Pro Webmasters SE that goes into more detail about implementing HSTS in .htaccess: https://webmasters.stackexchange.com/a/112264/52912