Remove Canonical and Shortlink from Drupal Homepage

Last modified: 
Wednesday, March 9th, 2016
Topics: 
Drupal

Drupal generates canonical link relationships in the HTML head output. A problem arises when a canonical URL combines with Drupal's clean URL redirects on the front page to create an infinite redirect loop which the Facebook linter doesn't approve of one bit. This may cause Facebook to refuse to pull in images from your front page.

One solve for this is to strip the canonical and shortlinks from the front page altogether. You could alter this to create custom canonical and shortlinks if you prefer.

/**
 * Alter the html head section of every page.
 * @param $head_elements
 */
function MYMODULE_html_head_alter(&$head_elements) {
    _MYMODULE_html_head_alter_frontpage_links($head_elements);
}


/**
 * Rewrites the canonical and shortlinks on the front page because Facebook
 * doesn't like the redirect loop Drupal creates.
 * @param $head_elements
 */
function _MYMODULE_html_head_alter_frontpage_links(&$head_elements) {
  if (drupal_is_front_page()) {
    foreach ($head_elements as $key => $element) {
      if (isset($element['#attributes']['rel'])) {
        switch ($element['#attributes']['rel']) {
          case 'canonical':
            // Prevent redirect loop on home page.
            unset($head_elements[$key]);
            break;
          case 'shortlink':
            // We don't need a shortlink on the front page.
            unset($head_elements[$key]);
            break;
        }
      }
    }
  }
}


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.