Using the Link Rel Canonical Tag - Implementing a Canonical Version, First Scenario (
Page 4 of 5 )
This scenario focuses on a domain using a non-secure protocol (http://) and www as the canonical version of the site. Using the steps explained earlier, the resulting script should be:
<?php
//place this script between the <head> and </head> section of your header.php or related dynamic website template
//such as index.php, product_info.php in the OsCommerce templates
//this script is applicable when the CANONICAL PROTOCOL IS HTTP AND USING WWW VERSION.
//this script is NOT APPLICABLE to a subdomain of a main domain.
//Example: if your canonical version is www.mysite.com, you should NOT be using the script in any of its subdomain.
//First step eliminate any session IDs in the URL:
$requestedurl = $_SERVER["REQUEST_URI"];
//Define array of most common open source session IDs
$id=array('osCsid','zenid','PHPSESSID');
if (preg_match("/osCsid/i", $requestedurl))
{
$x=0;
}
elseif (preg_match("/zenid/i", $requestedurl))
{
$x=1;
}
elseif (preg_match("/PHPSESSID/i", $requestedurl))
{
$x=2;
}
if ((preg_match("/osCsid/i", $requestedurl)) || (preg_match("/zenid/i", $requestedurl)) || (preg_match("/PHPSESSID/i", $requestedurl)) )
{
//URL is session ID based
$position=(strpos($requestedurl,$id[$x]))- 1;
}
else
//no session ID
{
$position=strlen($requestedurl);
}
//trim the URLs any session ID
$cleanrequest=substr($requestedurl,0,$position);
//set protocol to http:// since this the canonical protocol
$protocol='http://';
//check if the server name contains www
if (preg_match("/www/i", $_SERVER["SERVER_NAME"]))
{
//the URL is using the www version
//display the complete canonical URL without any session ID
$canonical=$protocol.$_SERVER["SERVER_NAME"].$cleanrequest;
}
else
{
//append the canonical www version to the server name and display the canonical www version
$URL='www.'.$_SERVER["SERVER_NAME"];
$canonical=$protocol.$URL.$cleanrequest;
}
//Final step defining the final link rel canonical element
echo '<link rel="canonical" href="'.$canonical.'" />';
?>
The good thing about this script is that it will automatically remove the session IDs of the most common e-commerce templates, such as OsCommerce, Zen Cart and CRE loaded.
The resulting URL is SEO-friendly without the session IDs in it, while using the http:// and the www canonical version.