For completeness, here's the simpler mod_alias alternative suggested by MrWhite. This also has the HSTS headers in the correct place and, as recommendable, subdomains included & with preloading. First the three redirecting virtual hosts and then the actual virtual host serving content.
<VirtualHost *:80>
ServerName example.com
Redirect permanent / https://example.com/
</VirtualHost>
<VirtualHost *:80>
ServerName www.example.com
Redirect permanent / https://www.example.com/
</VirtualHost>
<VirtualHost *:443>
ServerName example.com
Redirect permanent / https://www.example.com/
# The mandatory SSL* directives.
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
</VirtualHost>
<VirtualHost *:443>
ServerName www.example.com
DocumentRoot /var/www/html
# The mandatory SSL* directives.
# . . . whatever else you may have here
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
</VirtualHost>
Naturally, this requires both mod_alias and mod_headers loaded. Wrapping the Header
directives inside <IfModule>
sections would avoid errors on missing mod_headers module, but then you would not have HSTS enabled, and this was titled as redirection with HSTS.
The two <VirtualHost *:80>
blocks are there because:
- there's a limitation: you can't use the variable
%{SERVER_NAME}
with Redirect
.
- with HSTS it's recommended to redirect first to the HTTPS and then to the canonical name.
For the wildcard *.example.com
redirection I'd add a ServerAlias
to the VirtualHosts *:80
redirecting first to the domain apex and then again there on the HTTPS. As the www
is included in the *.example.com
, you won't even need the additional <VirtualHost *:80>
for it:
<VirtualHost *:80>
ServerName example.com
ServerAlias *.example.com
Redirect permanent / https://example.com/
</VirtualHost>
<VirtualHost *:443>
ServerName example.com
ServerAlias *.example.com
Redirect permanent / https://www.example.com/
. . .
This way the user...
- Enters URL
http://anysub.example.com/
.
- Gets redirected to
https://example.com/
(or is already on the same configuration, if entered https://anysub.example.com/
, or if the HSTS policy is already in the cache).
- Sees the HSTS header, protecting all
(*.)*.example.com
including anysub.example.com
.
- Gets finally redirect to the canonical
https://www.example.com/
.