Search Engine Friendly 301 Redirect in PHP
If you are finding that the www.sitename.com and sitename.com version of your site are both being indexed by the search engines you could hit an issue with the search engines seeing duplicate content – after all most sites have both site names resolving to the same underlying file structure. This can also be an issue for people with parked domains – if you’ve brought multiple domains with the common misspellings of your company name (for example), if the search engines index the parked domain you could have a duplicate content issue. Another issue is having links pointing to the various site names dilutes their value, but pointing them all at just one domain name you’ve got a better chance of higher rankings.
One of the best ways around this issue is to redirect all traffic destined for the domains you don’t want to get indexed to the site name you do want to get indexed. By using a 301 redirect the value of the links will also be redirected to the main site name.
PHP 301 Code
Place the following code into the header of any php document and it will redirect the page access to the correct site name. while preserving the script name and the query arguments.
// If the server name is not www.sitename.com we can do the redirect to www.sitename.com. // The only time we can is if the method is a GET // (no way to pass along the POST arguments) and its on port 80 (don't want to redirect the SSL). if ( strcmp( strtolower( $_SERVER['HTTP_HOST'] ) , "www.sitename.com" ) != 0 && strcmp( strtolower( $_SERVER['REQUEST_METHOD'] ) , "get" ) == 0 && $_SERVER['SERVER_PORT'] == 80 ) { header("Location: http://www.sitename.com" . $_SERVER['REQUEST_URI'] ); header("HTTP/1.0 301 Moved Permanently"); exit ; }