Canonical URLS in Drupal

By default, Drupal will insert a <link rel="canonical"> tag in the head of each page on your site. The problem is Drupal inserts a relative URL rather than a more helpful absolute path. The other issue, is if you have a mobile version of the site, you need to account for that too.


Remove default Drupal canonical tag. Add this code to template.php:

* Canonical Link fix
* Canonical link generation in html.tpl.php
function [YOURTHEME]_html_head_alter(&$head_elements) {
 foreach (preg_grep('/^drupal_add_html_head_link:canonical:</', array_keys($head_elements)) as $key) {

Add this below the <title> tag in html.tpl.php:

<?php if( variable_get( 'site_frontpage' ) == current_path() ) : ?>
  <link rel="canonical" href="" />
    <link rel="alternate" href="" media="only screen and (max-width: 640px)" />
  <?php else : ?>
    <link rel="canonical" href="<?= url(current_path()); ?>" />
    <link rel="alternate" href="<?= url(current_path()); ?>" media="only screen and (max-width: 640px)" />
  <?php endif; ?>