A Simple Solution To Add rel=”canonical” Sitewide

Adding a rel=”canonical” link to the head of a webpage is extremely important for SEO. Very simply, a rel=”canonical” link tells Google that multiple pages on your website are actually the exact same page.

Why do I need a rel=”canonical” ?

Lets take my home page for example, there might be four incoming links from other websites, which go to the following four urls:
http://www.webdevbydoing.com
https://www.webdevbydoing.com
http://www.webdevbydoing.com/
http://www.webdevbydoing.com?query=param

We need to make sure that google understands that these four different urls actually deliver the same content, and that only the first one should be prioritized and shown in search results. On most websites, going through every single page and manually adding it in isn’t realistic. Even if you’re using a CMS which automatically adds the canonical link in, they all just point to the current page, which doesn’t help with our problem. For example, I use Yoast which does a great job with a lot of things, but by default, if you go to http://webdevbydoing.com, Yoast puts this in the <head>

<link rel="canonical" href="http://webdevbydoing.com" />

And if you go to the secured version at https://www.webdevbydoing.com, this appears in the <head>

<link rel="canonical" href="https://webdevbydoing.com" />

So our problem still exists. The solution? This php code script below will completely standardize your rel=”canonical” link

	<?php
		// add canonical link 
		$actual_link = "http://" . $_SERVER["HTTP_HOST"];
		if ($_SERVER['REQUEST_URI'] != "/"){
			$actual_link .=  strtok($_SERVER["REQUEST_URI"],'?');
		}
		echo '<link rel="canonical" href="' . $actual_link . '" />';
	?>

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>