phphtmlhyperlinkcanonical-link

How do I remove a file extension in the HTML HEAD metadata for canonical URLs?


I have a website that requires files to be served without the file extension. For example, the URL http://www.example.com/foo.php should be accessible as simply http://www.example.com/foo.

However, please forgive me as I am a novice at PHP, but I would also like the <link rel="canonical ...> in the HTML file's HEAD metadata to show this too.

So far, I have got:

<link rel="canonical" href="<?php echo $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME']; ?>">

This brings up the full URL, including the file extension.

Is there anybody out there with a it more PHP knowledge than myself that can modify that above line of code to exclude the file extension?

Thanks in advance!


Solution

  • You can try removing the extension using str_replace

    $string_with_extension = $_SERVER['REQUEST_SCHEME'] . '://' .$_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];
    
    $extension = ".php";
    
    $new_string = str_replace($extension,"",$string_with_extension);
    

    Simply, your just replacing the extension with "" or nothing resulting to your desired url.

    <link rel="canonical" href="<?php echo $new_string; ?>">