Enforcing HTTPS & WWW prefix with Apache .htaccess redirects using cPanel

First post is simple.  I wanted a simple way to enforce both HTTPS (TLS/SSL) and the WWW prefix while gracefully handling whatever the user enters.

I am not going to get into the age old debate.  Every domain admin must make the choice.  The combination of sub-domain DNS round-robin, cookies, and the that every non-technical user expects WWW, I chose to redirect to the WWW prefix.  The wrinkle was I also wanted to enforce HTTPS.  After searching for a few minutes I cobbled together a working and flexible solution which does not hard code the domain name.  Kudos to this stackoverflow thread which did most of the heavy lifting.

RewriteOptions inherit
RewriteEngine On

#First rewrite any request to the correct one (i.e. adding "www." if it does not exist)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#After checking and adding "www." if necessary, then rewrite to HTTPS:
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

For those new to .htaccess configuration files (and since I am using cPanel) here is a simple article to get you started and how to apply the above config.

Speaking of cPanel/WHM and HTTPS, an honest referral to EZPZ Hosting.  Dan and his team have been superb since I became a customer back in 2010.  Their reseller accounts include unlimited free, basic SSL certificates.

EZPZ Hosting
ezpzlogo

Leave a Reply

Your email address will not be published. Required fields are marked *