Canonical URL 301 redirect as www or non-www with htaccess or php

7th December 2012

There are different opinions on the benefits and negatives of having www and not having www in your domain name, but one thing that’s for sure, is you need to make a decision and only have your site resolve to one. It is not good practice for your website to resolve to both, this is because Google and other search engines may see this as being a duplicate site and penalise you in their results.

We personally prefer the non www option, it just looks cleaner and takes away unnecessary characters from your domain name, but this is purely our personal preference. From experience we have found the .htaccess solution to be the best and easiest to implement, but if your website is on a Windows server, or you do not want to play around with your .htaccess file, you can do this using PHP.

Solution using .htaccess file

If you want to have www. in your domain, use:

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

If you don’t want to have www. in your domain, use:

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

Solution using PHP

IMPORTANT: You need to make sure that this code is included on all pages of your site.

If you want to have www. in your domain, use:

<?php
if ($_SERVER['HTTP_HOST'] != 'www.domain.com'){
     header("Location: http://www.domain.com".$_SERVER['REQUEST_URI']);
}
?>

If you don’t want to have www. in your domain, use:

<?php
if ($_SERVER['HTTP_HOST'] == 'www.domain.com'){
     header("Location: http://domain.com".$_SERVER['REQUEST_URI']);
}
?>

Last updated by at .

Comments...


Rauf
25th February 2013

Thanks, for the solution in PHP. I am beginner in PHP. Please can you tell me where I need to put php code ? do I have to add in each php file?

Thanks in advance!

Hi, yes you either have to add it to each page or put it within a php document and included it to every page.


lite14
22nd April 2013

This is a very nice article on htaccess redirector i like your article.

Got An Opinion On This Article?

Share your comments with us...


*