HTTPS Canonical Tag for SEO – PHP Code to Automatically Detect Secure Version of Webpage But Block from Search Engines

I noticed one of my websites was being indexed and cached in Google with the HTTPS version of some pages, which is not good especially for duplicate content. I searched for various solutions and I came across this nifty PHP code to automatically detect which version of the URL is being accessed. If it’s the secure or HTTPS version of the URL, then it automatically inserts a rel=canonical tag so search engines know to only index the non-secure version of the URL. It works perfectly and I wanted to make sure I remembered it by putting on this blog.

Check it out -

<?php
$currenturl= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

//Check if it is using the secure https port which is 443
if ($_SERVER["SERVER_PORT"] == “443″) {

//connected to secure port, formulate the http canonical version
$canonicalversion=”http://”.$currenturl;

//echo the canonical version to the HTML as link rel canonical tag

echo ‘<link rel=”canonical” href=”‘.$canonicalversion.’”/>’;
}
?>

<?php
$currenturl= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if ($_SERVER["SERVER_PORT"] == “443″) {
$canonicalversion=”http://”.$currenturl;
echo ‘<link rel=”canonical” href=”‘.$canonicalversion.’”/>’;
}
?>