With SEO being an important factor in wed design, it is recommended to use either WWW or non-WWW for your site URL; it is not wise to use both. This can easily be done by using .htaccess. There are situation when using .htaccess is not possible and the only means to do the redirect is by using PHP. I have recently found myself in this situation and I decided to post this simple code snippet that will redirect non-WWW URL’s to the WWW URL.
The code is:
// Check if we need to perform a redirect
$fetchedURL = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
if (substr($fetchedURL,0,4) != 'www.') { // Make sure the URL does not use www.
// Let do the redirect
header( "HTTP/1.1 301 Moved Permanently" );
header('Location: http://www.'.$fetchedURL.((isset($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : '')); // Append the REQUEST_URI
}
The code is very simple and is documented. I hope some may be able to make use of this script.
The above code will take the provided URL and forward it to the WWW URL. This will retain the full URL path. I.E.: http://son9ne.com/index.php?somevar=somevalue will be changed to http://www.son9ne.com/index.php?somevar=somevalue
Copyright ©2009 Jeremy Simkins. Theme Design by Noe Ruiz