How to make «rel=canonical» in PHP for different CMS

On different CMS, sometimes URL are built with parameters, with a slash at the end or without it. Because of this, sometimes, during the SEO progress, duplicate pages appear, which should not be. Therefore, you should use rel=canonical to avoid problems with SEO promotion.

Below is the code that should be inserted between <head></head> or done on function.

	if((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443){
		$protocol = 'https://';
		$protocol = 'http://';
	$url = $protocol.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
	$urlend = strrpos($url, '?', -1); // Find and delete all parameters (page number, filter parameters, etc.)
	$url = substr($url, 0, $urlend);
	if(mb_substr($url, -1) == '/'){ // Here we leave, if the links on the site do not end with / or delete if end with /
		$url = substr($url, 0, -1);

    echo '<link rel="canonical" href="'.$url.'"/>';

Aboute code.
First we determine whether the site is opened by a secure protocol or not.
Then we collect our URL from the protocol ($protocol), domain ($_SERVER[‘SERVER_NAME’]) and links ($_SERVER[‘REQUEST_URI’]).
Next, we determine whether the URL has parameters or not ($_SERVER[‘QUERY_STRING’]). If there is, delete them, they are not needed for the tag.
And at the end (not necessarily) remove the slash if the links are formed without it. It is also useful not to use 301 redirect, which conflicts with the processing of 404 pages on different CMS.


If you have any questions, want to get individual advice or you have an interesting offer, you can contact via the feedback form.

Or write to the email

By submitting the form, you agree to our privacy policy