.htaccess Rules to Enforce Both HTTPS and WWW

My goal is to have a set of Apache rules to enforce both HTTPS and the www. version of a site’s domain. I’ve been working on some rules to include in my .htaccess file for WordPress installs (and basically for any other sites too). I’ve tried to write the rules such that there would never be 2 redirects, one to enforce https and then another to enforce www. I was just looking to get a few opinions on what I have so far and to see if anybody sees any holes or flaws in my logic or suggestions for better, more succinct ways to achieve the same thing. Here is what I currently have:

# Below matches requests to primary domain w/out www. prefix
# We don't worry about reqs beginning w/ hyphen b/c those won't make it to our server
# We don't allow periods in our match to rule out any sub-domains
RewriteCond %{HTTP_HOST} ^(?!www\.)[a-z0-9-]{2,}\.[a-z]{2,6}$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

# Rewrite any non-https www request to https
RewriteCond %{HTTPS} !On
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [L,R=301]

# Redirect any non-https request to valid sub-directories to https
RewriteCond %{HTTPS} !On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^([a-z0-9]+\.[a-z0-9-.]{2,}\.[a-z]{2,6})$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

One thing I noticed, at least with my local WAMP setup, is that if I make a request to a subdomain that doesn’t exist in the setup, it does not get redirected to HTTPS (just gets a 404 not found), even though it matches the 3rd set of rules above. I don’t have much experience with HTTPS yet, so just wondering if this is how it should be or if this risks sending any info unencrypted.

Thanks!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.