Redirect non-www to www and http to https using .htaccess

November 29, 2016
Posted in: Code Snippets, How To, Web Development, WordPress

Whether you have a WordPress website or not, it’s always good SEO practice to use one domain for your site, and avoid allowing both the www and non-www versions.

Google Search, as well as many other web technologies prefer the high security of SSL-enabled sites – for example, sites can no longer request your location via the GeoLocation API in Chrome unless the site uses https. Other technologies like Chrome’s Physical Web implementation will completely ignore beacons advertising insecure URLs.

The fix? A few lines in your .htaccess file.

Simply add this to the beginning of our file:

# Redirect non-www to https + www
#  becomes
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Redirect non-https to https
#  becomes
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Please be aware that this won’t work with certain load balancers, but should work for the majority of typical servers.

The idea behind the two blocks of code is that we want the user to get to the final domain (with security) as quickly as possible.

The first block redirects all non-www traffic to the the www domain using the https protocol. This will do the following:

  •  =>
  •  =>

And the second block redirects any non-https traffic to https.  This ignores non-www traffic because it’s already been taken care of in the first block. This will do the following:

  •  =>

So, with only a few lines added to your .htaccess file, you can now ensure that all users are navigating your site using the same domain.

Making sure Google knows what you prefer

Now that your site is forcing https and www, you should be sure to add all variants of the site to Google Search Console.  Keep in mind that there are a few domains to consider:

  1. (primary domain – www, https)
  2. (www, non-https)
  3. (non-www, https)
  4. (non-www, non-https)

Once all variants have been added to Search Console, you can set your preferred domain.

The rules we’ve created are using 301 redirects (permanent redirects), so they’ll also notify Google that the old indexed pages should be re-addressed or removed.

Scott Buckingham

President / Owner
613-801-1350 x101
[email protected]
Scott is a WordPress expert who has worked on hundreds of web design and development projects. He excels at finding creative ways to solve technical problems. View full profile