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:
[php]
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain.com$
RewriteRule (.*) http://www.domain.com/$1 [R=301,L]
[/php]

If you don’t want to have www. in your domain, use:
[php]
RewriteEngine On
RewriteCond %{HTTP_HOST} !^domain2.com$
RewriteRule (.*) http://domain2.com/$1 [R=301,L]
[/php]

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']);
}
?>
[/php]

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']);
}
?>
[/php]

Related Terms:
Posted on 7th December 2012 by in htaccess, SEO Hampshire, SEO Portsmouth, SEO Tips
  • http://Website Rauf

    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!

    • stuart

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

  • http://www.nigerialocalnews.com lite14

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

Web Agency Portsmouth
where to go from here? get in touch OR

give us a call on 02392 123 538

Let's be friends! More...
Facebook Twitter Google+
Like & Follow Facebook Twitter Google+
Share the love, share this page! Facebook Twitter Google Digg Reddit LinkedIn Pinterest Email
Close [X]
Web Design South Coast
Areas We Cover

Here are some of the local areas we provide with web design and digital marketing services. These are just some examples, we work with clients all over the UK and across the globe.

Our Services
Close [X]
The Web Taylor
Harcourt Close Waterlooville, Hampshire PO8 8JL
02392 123358