<link rel=“canonical” href=“/relative/url” />
-
30-01-2021 - |
Question
Drupal 8 creates <link rel="canonical" href="/relative/url" />
by default. support.google.com says:
Use absolute paths rather than relative paths with the rel="canonical" link element.
Use this structure: https://www.example.com/dresses/green/greendresss.html Not this structure: /dresses/green/greendress.html
I used the Google Search Console URL Inspection and found Google does not recognize relative urls as canonical. It says:
User-declared canonical N/A
I believe this is causing some indexing problems for our multiple language website. How can we convert the canonical urls to absolute as recommended by Google?
Solution 2
The following function updates the rel tags in the head section of all pages on a website. The "revision" and "shortlink" tags are deleted using unset(). The "canonical" tag is converted from a relative to an absolute url. This function should be called from modulename_preprocess_html() of your custom module.
function canonical_shortlink_revision(&$variables) {
foreach($variables['page']['content']['system_main']['#attached']['html_head_link'] as $key => $value) {
if( ($value[0]["rel"] === "revision") || ($value[0]["rel"] === "shortlink") )
unset($variables['page']['content']['system_main']['#attached']['html_head_link'][$key]);
if($value[0]["rel"] === "canonical") {
$href = $variables['page']['content']['system_main']['#attached']['html_head_link'][$key][0]["href"];
$href = \Drupal::request()->getSchemeAndHttpHost() . $href;
$variables['page']['content']['system_main']['#attached']['html_head_link'][$key][0]["href"] = $href;
}
}
}
OTHER TIPS
The metatag module gives you the ability to overwrite the 'canonical' metatag:
- On the module's settings page (
/admin/config/search/metatag
) - Edit the
General
type - Under
Advanced
you'll find the Canonical field - Set the field's value to
[current-page:url:absolute]
- Save
That should do it. The instructions above are for Drupal 8.
Update 1:
If you are comfortable using hooks and working with PHP you may also use a theme hook (hook_page_attachments_alter
) to achieve the same thing. Here's the api spec on drupal.org for the function.