Magento 2 Developement

Magento 2: Canonical URL for homepage

Canonical url point exactly to canonical page for similar or duplicate pages ( Consolidate duplicate URLs ). I assume you are doing it to specify which URL that you want people to see in search results. Magento 2 has several options to set canonical url for homepage.

TIP: Check you current canonical URL using URL Inspection tool

Update Canonical URL via theme xml

Create or update following file for your current theme.
If you are not sure about this, check Content > Design > Configuration to find active theme.

app/design/frontend/<vendor>/<theme>/Magento_Cms/layout/cms_index_index.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <link rel="canonical" src="https://www.example.com" src_type="url" />
    </head>
</page>

After that run following commands in Magento 2 root folder:
php bin/magento setup:static-content:deployDeploys static view files
php bin/magento cache:cleanCleans cache type(s)

Update Canonical URL via Module

Module will contain 3 files. Basically 2 of them are mandatory for any module and 3rd is responsible for layout update. You need to update <vendor> and <module> to your values.

app/code/<vendor>/<module>/registration.php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    '<vendor>_<module>',
    __DIR__
);

app/code/<vendor>/<module>/etc/module.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nonamespaceschemalocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="<vendor>_<module>" setup_version="1.0.0"</>
</config>

app/code/<vendor>/<module>/view/frontend/layout/cms_index_index.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <link rel="canonical" src="https://mydomain.com" src_type="url" />
    </head>
</page>

To install module run following commands in Magento 2 root folder:

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy
php bin/magento cache:clean

If you want to disable or uninstall magento 2 module – check following links:
Magento 2: How to disable module
Magento 2: How to uninstall module

Leave a Reply

Your email address will not be published. Required fields are marked *