301 Redirect for www or non www with htaccess or php

What is a canonical url?

Matt Cutts describes canonicalization in the following way…

Canonicalization is the process of picking the best url when there are several choices, and it usually refers to home pages. For example, most people would consider these the same urls:

But technically all of these urls are different. A web server could return completely different content for all the urls above. When Google “canonicalizes” a url, we try to pick the url that seems like the best representative from that set.

www. or non www.

People have different opinions on whether or not website’s should use www or not within their website’s URLs. The truth is, it doesn’t really matter a whole lot. You will see websites with both that rank high in the search engines, proving that it can’t make that much difference. The most important thing is that you make a decision and choose! It is not good practice for your website to have both. This is because search engines may see this as being a duplicate site and penalise you in their search results.

URL canonicalization for www or non-www should be done using a 301 (impermanent) redirect which can be implemented using your htaccess file and PHP. See the examples below.

Canonical URL Using .htaccess

If you do want www.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain.com$
RewriteRule (.*) http://www.domain.com/$1 [R=301,L]

If you don’t want www.

RewriteEngine On
RewriteCond %{HTTP_HOST} !^domain2.com$
RewriteRule (.*) http://domain2.com/$1 [R=301,L]

Canonical URL Using PHP

You must ensure that this code is included within all pages of your site.

If you do want www.

<?php if ($_SERVER&#91;'HTTP_HOST'&#93; != 'www.domain.com'){
header("Location: http://www.domain.com".$_SERVER&#91;'REQUEST_URI'&#93;);

If you don’t want www.

<?php if ($_SERVER&#91;'HTTP_HOST'&#93; == 'www.domain.com'){
header("Location: http://domain.com".$_SERVER&#91;'REQUEST_URI'&#93;);
Free Graphics, Icons, Tutorials
Free Graphics Free Christmas Icon Pack PSDFree Christmas House PSD GraphicFree Rounded Santa Icons PSDFree Skip Graphics PSDFree Cassette Vector GraphicFree Circular Icon Graphics Pack
Sharing is caring...
Like & Follow
Share the love, share this page! Facebook Twitter Google Digg Reddit LinkedIn Pinterest Email
Close [X]
The Web Taylor
Harcourt Close Waterlooville, Hampshire PO8 8JL
02392 123358