8 – Home Page rel=”canonical”


You can use metatag module to adjust metatags like these.

After installing you can visit the settings page /admin/config/search/metatag and there is a specific set of metatags to adjust for front page. Edit those settings and adjust canonical but I believe by default it sets this to (site:url) which should be OK.

Alternatively or if you don’t want to install a module just for this you can do it using hook_preprocess_html in your THEMENAME.theme

function THEMENAME_preprocess_html(&$variables) {
  //if not front page do nothing
  if(! Drupal::service('path.matcher')->isFrontPage())
    return ;

  //unset if set
  foreach ($variables('page')('#attached')('html_head') as $key => &$value) {
    if ($value(0)('#tag') == 'link' && $value(0)('#attributes')('rel') == 'canonical') {
      unset($variables('page')('#attached')('html_head')($key));
      break;
    }
  }

  //add canonical
  $canonical = (
    '#type' => 'html_tag',
    '#tag' => 'link',
    '#attributes' => (
      'rel' => 'canonical',
      'href' => '/',
    ),
  );
  $variables('page')('#attached')('html_head')() = ($canonical, 'canonical');  
}