Preserve Domain Alias

You need to set the canonical hostname (ie. with www) in the WordPress dashboard… Under Settings > General and set the appropriate “WordPress Address (URL)” and “Site Address (URL)” properties.

Alternatively, these values can be hardcoded in wp_config.php by defining the WP_HOME and WP_SITEURL constants respectively.

Reference:
https://codex.wordpress.org/Changing_The_Site_URL

SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq "example.com"
ErrorDocument 403 https://example.com

Bit of an aside, but this is a very roundabout (not recommended) way of redirecting to HTTPS. Yes, this will trigger a 302 (temporary), not a 301 (permanent) redirect. This only redirects at all because of a side effect of ErrorDocument. And it only redirects to the document root, the requested URL is lost.

This code actually blocks access to the HTTP-only site and triggers a 403 Forbidden. Because you have set an absolute URL as the 2nd argument to the custom 403, Apache triggers an external (302) redirect to the URL, the root of your site.

If you don’t have access to the server config, then this redirect is normally achieved using mod_rewrite in .htaccess. For example:

RewriteCond %{HTTPS} !on
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]

This would need to go before the existing WordPress directives in .htaccess.


Once you have set the appropriate hostname within WordPress, you can handle both HTTPS and www redirection in .htaccess if you wish (it would be slightly more efficient). For example:

RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} !www\.
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]

Make sure you clear your browser cache before testing.


I need the www. preserved only if the user entered it to begin with.

Unless you have a specific reason to do this, then this is generally a bad idea. It potentially creates duplicate content, although you can set a rel="canonical" tag in the head section to alleviate this, and you can specify a preference in Google Search Console (to avoid both hosts being indexed). But the stats will be split between them. How are you setting cookies? If you want cookies shared between both www and non-www (login, sessions, etc.), you’ll need to ensure that cookies are set on the apex domain, regardless of which host is accessed – I don’t believe this is the default behaviour.

Anyway, if you want to redirect HTTP to HTTPS but preserve whatever host has been accessed (www, non-www or xyz alias) then this is a much simpler redirect as you can reference the HTTP_HOST server variable. For example:

RewriteCond %{HTTPS} !on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]