PHP variable to deploy canonical tag (self-referencing)


Freelance Technical SEO
Staff member
Use this PHP variable snippet to deploy a self-referencing canonical tag to your PHP (semi dynamic & dynamic) powered website.

Add the following to your head section
<?php $canonical="https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; echo "<link rel='canonical' href=$canonical>"  . "\n"; ?>

If the variable is not required, then use this instead
<link rel="canonical" href="<?php echo "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>">

Let's break this down, the

Is calling the domain name (HOST), and the second part is calling the URI

I would recommend that you enforce a rule to have a trailing forward-slash or a rule to enforce without a trailing forward-slash. Otherwise you're prone to creating a canonical tag for both with or without trailing slash, and, that is not good for SEO.

Comment below if you need any help with this.