Remove the WWW Prefix for all URLs via PHP

Canonical URLs are important for maintaining consistent linkage, reducing duplicate content issues, and increasing the overall integrity of your site. In addition to cleaning up trailing slashes and removing extraneous index.php and index.html strings, removing the www subdirectory prefix is an excellent way to shorten links and deliver consistent, canonical URLs.

Of course, an optimal way of removing (or adding) the www prefix is accomplished via HTAccess canonicalization:

# universal www canonicalization via htaccess
# remove www prefix for all urls - replace all domain and tld with yours
# http://perishablepress.com/press/2008/04/30/universal-www-canonicalization-via-htaccess/

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^domain\.tld$       [NC]
RewriteRule ^(.*)$       http://domain.tld/$1 [R=301,L]

Unfortunately, not everyone has access to their HTAccess files or Apache configuration file. Fortunately, the same comprehensive (i.e., site-wide) URL canonicalization is easily achieved via PHP:

<?php 
if(!strstr($_SERVER['HTTP_HOST'],'www.')) 
return;
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://'.substr($_SERVER['HTTP_HOST'],4).$_SERVER['REQUEST_URI']);
exit(); 
?>

Paste that code at the top of your PHP-formatted web pages and you’re good to go. For example, if you are using WordPress, you would place the PHP canonicalization script into your active theme’s header.php file. You could also copy the script into your theme’s custom functions.php file, or even upload it to your plugins directory as run it as a plugin. Regardless of which implementation method you use, once the script is in place, you can kiss the www goodbye!