skip to Main Content

I’ve search around on SO, but can’t find an exact answer to my needs.

Generating a URL is pretty easy…

Like so:

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

But, the issue with this is, the $_SERVER['REQUEST_URI']) will always fetch the current file in use, so the canonical URL could potentially change.

So it could flick between www.example.com/hello.php and www.example.com/hello/, and many other variations depending on how the user accesses your site.

How do I make it so it’s always the same url? (preferably without .php)

4

Answers


  1. Chosen as BEST ANSWER

    Worked it out myself, pretty basic:

    <?php
    $fullurl = ($_SERVER['REQUEST_URI']);
    $trimmed = trim($fullurl, ".php");
    $canonical = rtrim($trimmed, '/') . '/';
    ?>
    

    Then...

    <link rel="canonical" href="https://example.com<?php echo $canonical ?>" />
    

    I'm sure there's different methods, but it works for me.


  2. This is what i do.

    <?php
    
    // get the rigth protocol
    $protocol = !empty($_SERVER['HTTPS']) ? 'https' : 'http';
    
    // simply render canonical base on the current http host ( multiple host ) + requests
    echo $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    
    ?>
    
    Login or Signup to reply.
  3. I think your scripts require a bit of sanitisation, am I right?
    I mean, if your page is

    https://example.com/test.php
    

    but a malicious – but harmless – person does

    https://example.com/test.php/anotherThing.php
    

    your canonical would become

    https://example.com/anotherThing.php
    

    you wouldn’t want that to happen, though, am I right? Especially if the malicious person is not harmless and does worst things with your urls…

    Login or Signup to reply.
  4. This will remove query parameters like ?search=abc&page=32

    Option 1:

    $url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . strtok($_SERVER['REQUEST_URI'], '?');
    

    Option 2 (does the same) :

    $url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
    

    Then echo

    echo '<link rel="canonical" href="' . $url . '" />';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search