The Coder

Remove WWW's

Original posted by: Admin on 28-01-2007

This tutorial will teach you a method of forcing all your visitors to look at 'domain.com' instead of 'www.domain.com' or vise-versa.

This is also a good SEO technique that a lot of major sites use, it can be done via the htaccess file but if you don't know the know how or if your server doesn't allow you to use that file you can do it a simple PHP script.

First off we have to discover what the person is viewing, to do this we must do the following


echo $_SERVER['HTTP_HOST'];


This will tell us what version of our site the visitor is looking at. For example if they are looking at 'http://www.thecoder.com.au' the HTTP_HOST will print 'www.thecoder.com.au' if they are looking at the non-www version then it will print 'thecoder.com.au'.

So with this we can write a simple little script to check what the start of the string looks like


if(substr($_SERVER['HTTP_HOST'], 0, 4) == 'www.') {
echo 'Is WWW version, redirect';
} else {
echo 'Isn't WWW version, no redirect';
}


With that simple if statement we can discover what version they are looking at, now all we have to do is redirect the visitor.


if(substr($_SERVER['HTTP_HOST'], 0, 4) == 'www.') {
header('Location: http://domain.com');
exit();
}


So now if the visitor goes to the WWW version of the site they will be redirected to the new version.

This script can be placed up the top of any of your pages, or if you want it can go into a general config file and even placed within a function.


function check_host() {
if(substr($_SERVER['HTTP_HOST'], 0, 4) == 'www.') {
header('Location: http://domain.com');
exit();
}
}

#Call Function
check_host();




Login to make a comment 0 Comments Found