phpseocanonical-link

Using PHP for canonical urls


I set the following rule in my .htaccess file to redirect example.com/index.php to example.com

RewriteCond %{THE_REQUEST} ^.*/index\.php 
RewriteRule ^(.*)index.php$ /$1 [R=301,L] 

Then I set my canonical as following in the header.php for all pages:

<link rel="canonical" href="https://www.example.com<?php echo $_SERVER['PHP_SELF']; ?>" />

However I noticed the canonical url sets to index.php instead of the root.


Solution

  • PHP_SELF is the name of the currently executing script.

    For example:

    http://www.yoursite.com/example/ -- --> /example/index.php http://www.yoursite.com/example/index.php -- --> /example/index.php http://www.yoursite.com/example/index.php?a=test -- --> /example/index.php http://www.yoursite.com/example/index.php/dir/test -- --> /dir/test

    If you want to generate seo friendly url to reference self source you need to set tag with site HOST+URI like this:

     <link rel="canonical" href="https://www.example.com<?=$_SERVER['REQUEST_URI']?>" />