Proper Rel Canonical Snippet

Hi lovely Kirbyists, long time no see! :grin:

As Kirby uses its own formating of params, it makes it possible to do Rel Canonical just right by soft-whitelisting these.

So in your header.php template:

<?php if( count(url::params()) ): ?>
    <link rel="canonical" href="<?= $page->url() . '/' . kirby()->request()->params() ?>">
<?php else: ?>
    <link rel="canonical" href="<?= $page->url() ?>">
<?php endif; ?>

Thus preventing some pretty common mistakes (see mistake #1) descibed by Google here Official Google Webmaster Central Blog: 5 common mistakes with rel=canonical
yoursite.com/blog/page:2 with a rel canonical to yoursite.com/blog is the most common mistake and prevents Google from indexing your entire pagination or simply decides to ignore rel canonical for your entire site.

Pretty handy if you have e.g. yoursite.com/blog/tag:cats …I mean, who doesn’t want these indexed.

Please feel free to improve on it, if it can be prettier or have any feedback :smiley:

3 Likes

You can always pour this into a custom page method, something like this (untested):

page::$methods['canonicalURL'] = function($page) {
  return count(url::params()) ? $page->url() . '/' . kirby()->request()->params() : $page->url();
};

and than use it in your header snippet like this:

<link rel="canonical" href="<?= $page->canonicalURL() ?>">

Please also note that you have to use href="" instead of content="".

1 Like

Nice, that’s much cleaner, thanks :slight_smile:

Aaarrgh nasty typo right there! I’ve corrected it :joy:

Enhanced it a bit more after some testing:

page::$methods['canonicalURL'] = function($page) {
  return $page->url() . r(params(), '/') . kirby()->request()->params();
};

If you prefer a trailing slash in the homepage canonical URL (most people do), it becomes:

page::$methods['canonicalURL'] = function($page) {
  return $page->url() . r(params() || $page->isHomePage(), '/') . kirby()->request()->params();
};
2 Likes