.htaccess redirect to https and www

Category: Blog • Posted by Jeff Starr • Post Date:

If your site is serving secure pages via the HTTPS protocol (i.e., via SSL/TLS), you may need a technique to redirect all HTTP requests to HTTPS. Then to go further with your canonicalization efforts, you may also want to redirect all www requests to non-www (or vice versa). Both of these techniques are essential for serving canonical versions of your web pages, so why not combine them into single, simple slice of .htaccess? Read on to learn how..

Redirect to https and www

The following .htaccess technique redirects qualified requests to the https and www versions of your web pages. Add to your site's root .htaccess file:

# Canonical https/www
<IfModule mod_rewrite.c>
	RewriteCond %{HTTPS} off [OR]
	RewriteCond %{HTTP_HOST} !^www\. [NC]
	RewriteCond %{HTTP_HOST} ^(.*)$  [NC]
	RewriteRule (.*) https://www.%1/$1 [R=301,L]
</IfModule>

This code does the following:

  1. Checks if mod_rewrite is available
  2. Checks if HTTPS is off, or if the request does not include www
  3. If either condition matches, the request qualifies and is redirected to the https/www address

When placed in the root .htaccess, this technique covers all requests, providing complete https/www canonicalization for your site. No editing is required with this code; it's entirely plug-n-play.

Redirect to https and non-www

To instead redirect all requests to https and non-www, use the following code instead of the previous:

# Canonical HTTPS/WWW
<IfModule mod_rewrite.c>
	RewriteCond %{HTTPS} off [OR]
	RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
	RewriteRule (.*) https://example.com/$1 [L,R=301]
</IfModule>

As before, place this code in the root .htaccess of your site. Here is what it's doing:

  1. Checks if mod_rewrite is available
  2. Checks if HTTPS is off, or if the request includes www
  3. If either condition matches, the request qualifies and is redirected to the https/non-www address

When placed in the root .htaccess, this technique covers all requests, providing complete https/non-www canonicalization for your site. Remember to replace the two instances of example.com with your own domain name.

Note: if your site is suffering from duplicate pages because of index.php appended to requested URLs, check out this post at WP-Mix.com that explains how to remove www and index.php from the URL.