Skip to content

How to switch stores directly without the store switcher’s redirect chain?

For SEO reasons we would like to switch stores directly without the default store switchers redirect chain.

The normal Magento store switcher creates a redirect chain when switching store. For example switching from example.de/baelle to example.com/balls does the following:

  • example.de/baelle
  • 302 -> example.de/stores/store/redirect
  • 302 -> example.com/stores/store/switch?___from_store=de&___store=en&data=hash&signature=hash
  • 302 -> example.com/balls

This is bad for SEO and leads to tons of unnecessary urls showing up in search engine crawls.

Our first idea was replacing the store switcher template and using MagentoStoreModelStoreSwitcherInterface::switch in order to create the target url.
Something like this:

<?php foreach ($website->getStoreCollection() as $_store): ?>
    <?php if (
        $_store->getId() != $block->getCurrentStoreId()
        && $_store->isActive()
    ): ?>
        <li class="view-<?= $block->escapeHtml($_store->getCode()); ?> switcher-option">
            <a href="<?= $block->escapeHtml(
                $viewModel->getDirectLink(
                    $_store,
                    $block->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true])
                )
            ) ?>" class="text-white">
                <?= $block->escapeHtml($viewModel->getStoreSwitchLabel($_store)) ?>
            </a>
        </li>
    <?php endif; ?>
<?php endforeach; ?>

And in the view model:

public function getDirectLink(Store $_store, string $currentUrl): string
{
    $currentStore = $this->storeManager->getStore();
    $redirectUrl = "{$currentUrl}?___from_store={$currentStore->getCode()}";

    /** MagentoStoreModelStoreSwitcherInterface $this->storeSwitcher */
    return $this->storeSwitcher->switch($currentStore, $_store, $redirectUrl);
}

But this messes with the cookies and does not seem to work properly. In MagentoStoreModelStoreSwitcherManageStoreCookie::switch Magento then deletes the store cookie and sets it based on the passed store. So if I am in de I will get the en cookie and the en based content.

My question is if there are already extensions that replace the default store switcher and do a simple link to the according url of the store the user would like to switch to. Or if not is there a better way to generate the url?