Cookie Consent by Free Privacy Policy Generator

Create (self-referencing) canonical tag with a PHP variable

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
Code:
<?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
Code:
<link rel="canonical" href="<?php echo "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>">

Let's break this down, the
Code:
https://$_SERVER[HTTP_HOST

Is calling the domain name (HOST), and the second part is calling the URI
Code:
  $_SERVER[REQUEST_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.
 
Back
Top