Please note an odd bug in Apache 2.2 (observed in Apache 2.2.15) that makes this difficult if you are using env=HTTPS
to control when the Header is being set. For some reason env=HTTPS
fails to fire during redirects, even if RewriteCond %{HTTPS}
on is used to control the redirect. So in my configuration that enables HTTP Strict Transport Security (HSTS), I use use a RewriteRule to create an environment variable called X_HTTPS
that has the same value as the HTTPS
, but which is not set to null when env=X_HTTPS
is evaluated:
SetEnv HSTS "max-age=31536000; includeSubDomains; preload"
# For some reason in Apache 2.2, HTTPS env variable is not available during redirects
RewriteCond %{HTTPS} on
RewriteRule ^.*$ - [ENV=X_HTTPS:%{HTTPS}]
# Set HSTS Header if the page is delivered via SSL
Header always set Strict-Transport-Security %{HSTS}e env=X_HTTPS
# Redirect SSL-only non-www page to www and quit
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^(.*)$ https://www.%{SERVER_NAME}%{REQUEST_URI} [R=303,L]
# Redirect ANY non-SSL page to SSL
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R=303,L]