Last active
September 22, 2022 11:36
-
-
Save ianpegg/283beac16cc71fdacff756f28a5b2f18 to your computer and use it in GitHub Desktop.
Rewrite requests for non-HTTPs or naked domain variations to the https://www scheme with only one 301 redirect. The ruleset includes checks to ensure we are in a production environment and that Let's Encrypt requests can pass through unmodified.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ---------------------------------------------------------------------- | |
# If a URL is requested over an insecure connection or if the URL request | |
# contains the naked domain variation, redirect the request to the | |
# https://www scheme. | |
# N.B there's nothing wrong with using naked domains, this is a stystic choice | |
# Adapted from: https://wp-mix.com/htaccess-redirect-http-to-https/ | |
# ---------------------------------------------------------------------- | |
<IfModule mod_rewrite.c> | |
# Check whether the request was made over an insecure protocol | |
# N.B. CloudFlare & other reverse proxies don't always set https to on, so check HTTP:X-Forwarded-Proto too: | |
RewriteCond %{HTTP_HOST} !\.test$ | |
RewriteCond %{HTTP:X-Forwarded-Proto} !https [OR] | |
RewriteCond %{HTTPS} off [OR] | |
# Check that we're not on staging and there is no 'www' subdomain prefix: | |
RewriteCond %{HTTP_HOST} !^(staging|www)\. | |
# Ignore Let's Encrypt certificate renewal checks: | |
RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/ | |
# If all conditions above match, rewrite to our secure www canonical domain: | |
RewriteRule (.*) https://www.yourdomain.co.uk/$1 [R=301,L] | |
</IfModule> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment