The link rel canonical tag lets you solve canonical issues for your URL without having to resort to 301 redirects or other potentially complicated approaches. This article explains how to take advantage of the tag in your PHP-powered web sites.
We will make a flowchart of the PHP script that will be able to place the canonical tag at the source of any non-canonical URL issues without the use of .htaccess or redirections.
Basically there are four domain canonical scenarios:
A domain using www and using the non-secure protocol (http://) as the canonical version. Most of the domains on the Internet fit into this scenario.
A domain using www and the secure protocol (https://) as the canonical version. A good example of this is PayPal.
A domain using non-www and using the non-secure protocol (http://) as the canonical version. This makes for easier typing of domain names in the browser for faster user access. A good example of this is Digg.
A domain using non-www and using the secure protocol as their canonical version. This alternative is not popular, although some good sites use this type of canonical version solution, such as https://launchpad.net/
Each of these URL canonical scenarios requires different PHP scripts, but the flow of implementation is the same. Here is an example that illustrates a site using http:// and www: as their canonical version.
Step 1: If the domain is using session IDs, this should be stripped off first as it is not needed as part of the canonical version.
Step 2: Check to see if the requested protocol is http://. If it is not, return the http version to the browser and append results with Step 3.
Step 3: If the requested URL dos not use www, append www to the URL; otherwise, return it to the browser.
The final canonical URL should:
Not use a session ID.
Contain the www version.
Use the canonical protocol, which is http://
In the rest of this article, I'll show you the recommended PHP canonical scripts for the four scenarios discussed above.