1

We created a home page as node/1850 which is specified in /admin/config/system/site-information. When I look at the generated code, I see:

<link rel="canonical" href="/node/1850" />

This results in Google listing the url of the home page as https://dom.ain/node/1850 which is not what we want.

What is the best way to correct this? I believe the following is correct.

<link rel="canonical" href="/" />

1 Answer 1

0

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'];  
}
4
  • Thank you for your feedback on this Giorgos. Mine seems to be a very basic problem that many core users can fall into. I hope I do not need to install a module to fix this one.
    – Greg Sims
    Jul 22, 2018 at 5:32
  • I'm not sure why, but my canonical data was here: $variables['page']['content']['system_main']['#attached']['html_head_link']
    – Greg Sims
    Jul 23, 2018 at 2:05
  • I tried giving "/node/1850" a URL Alias of "/home". Now the canonical is pointing to "/home" which is not much better.
    – Greg Sims
    Jul 23, 2018 at 19:42
  • greg just see under which branch is the canonocal.attached (as you already found) and use it ... the process is as outlined above
    – GiorgosK
    Jul 23, 2018 at 22:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.