Using .htaccess Force Adding www. to URL for SSL Certificate Authentication

In this day and age of many online scams it is necessary for every successful eCommerce storefront to have SSL Authentication for online purchases. These SSL Certificates are usually only good for one specific URL and are very picky as to whether or not the URL has to have “www.” attached to it. Here is a simple solution that we’ve created to force appending “www.” to the URL when trying to access a “https://” (http secure) address.

Some things you must know:

  • This will only work on an Apache server
  • You must have mod_rewrite installed under Apache

First, Create an .htaccess file if you don’t already have one. Then enter one of the following solutions based on your needs.

Force appending www. to only http secure (https://) requests

[sourcecode]

# Redirect non-www to www

	Options +FollowSymLinks
	# turn mod_rewrite on
	RewriteEngine On
	
	# If https send to https://www.
	RewriteCond %{HTTP_HOST} ^YOURDOMAIN.COM$ [NC]
	RewriteCond %{HTTPS} on
	RewriteRule ^(.*)$ https://www.YOURDOMAIN.COM/$1 [R=301,L]

[/sourcecode]

Force appending www. to both http (http://) and http secure (https://) requests

[sourcecode]

# Redirect non-www to www

	Options +FollowSymLinks
	# turn mod_rewrite on
	RewriteEngine On
	
	# If https send to https://www.
	RewriteCond %{HTTP_HOST} ^YOURDOMAIN.COM$ [NC]
	RewriteCond %{HTTPS} on
	RewriteRule ^(.*)$ https://www.YOURDOMAIN.COM/$1 [R=301,L]

	# If http send to http://www.
	RewriteCond %{HTTP_HOST} ^YOURDOMAIN.COM$ [NC]
	RewriteCond %{HTTPS} off
	RewriteRule ^(.*)$ http://www.YOURDOMAIN.COM/$1 [R=301,L]

[/sourcecode]

With these examples it is necesary for you to make sure that you replace “YOURDOMAIN.COM” to reflect the actual domain name of the website you will be using this on. Once you have done this, save your .htaccess file and upload it to the base directory of your website.

Believe it or not a few search engines distinguish your website as two different websites http://www.yourdomain.com and http://yourdomain.com. It is often considered good practice to add this htaccess rewrite to any website you create so that you can rest assured that your website is not being indexed as two different websites.