Skip to content

Instantly share code, notes, and snippets.

@angely-dev
Created October 7, 2022 16:57
Show Gist options
  • Save angely-dev/42818b92c3caa471631d686d79b1281c to your computer and use it in GitHub Desktop.
Save angely-dev/42818b92c3caa471631d686d79b1281c to your computer and use it in GitHub Desktop.
.htaccess redirect http2https and nonwww2www (meeting HSTS requirements)
#
# As required by HSTS, two redirects:
# 1) http2https (MUST be first)
# 2) nonwww2www
#
# https://webmasters.stackexchange.com/questions/84757/htaccess-redirect-non-www-to-www-with-ssl-https
#
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#
# Enable HSTS (HTTP Strict Transport Security).
# "always" is needed so that the Header is also added on redirects (i.e., the first http2https without nonwww2www).
#
# https://hstspreload.org/
#
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" env=HTTPS
#
# ...and so on...
#
@angely-dev
Copy link
Author

angely-dev commented Oct 7, 2022

Test with a Web Browser Capture

image

There are two redirects:

  • First: http to https
  • Second: non-www to www

Check HSTS preload eligibility

image

Now the domain can be preloaded!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment