Magento 2.2 - How to redirect url with store code to url without store code?
-
31-01-2021 - |
Question
The site is been indexed on Google with Store Code for each store view (it/en/gb/au) now the store codes are been removed from url, so all the links end up in a 404 error. How can I set an automatic redirect to the new links without store code for all the catalog? It may be possible with the .htaccess file?
From https://example.com/en/{something}.html to https://example.com/{something}.html
Solution
I've found the solution doing this simple Observer, I share the code, maybe it could be useful for someone else.
<?php
namespace VendorName\ModuleName\Observer;
use Magento\Framework\Event\ObserverInterface;
class ForceRedirectObserver implements ObserverInterface
{
protected $urlParts = [];
protected $storeManager;
protected $url;
public function __construct(
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\UrlInterface $url
) {
$this->storeManager = $storeManager;
$this->url = $url;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$request = $observer->getEvent()->getRequest();
$this->urlParts = parse_url($this->url->getCurrentUrl());
$pathChecker = $this->urlParts['path'];
if(strpos($pathChecker, 'it') == 1){
header("HTTP/1.1 301 Moved Permanently");
header("Location: " . $this->storeManager->getStore()->getBaseUrl() . substr($pathChecker, 4));
exit();
}
if(strpos($pathChecker, 'en') == 1){
header("HTTP/1.1 301 Moved Permanently");
header("Location: " . $this->storeManager->getStore()->getBaseUrl() . substr($pathChecker, 4));
exit();
}
if(strpos($pathChecker, 'gb') == 1){
header("HTTP/1.1 301 Moved Permanently");
header("Location: " . $this->storeManager->getStore()->getBaseUrl() . substr($pathChecker, 4));
exit();
}
if(strpos($pathChecker, 'au') == 1){
header("HTTP/1.1 301 Moved Permanently");
header("Location: " . $this->storeManager->getStore()->getBaseUrl() . substr($pathChecker, 4));
exit();
}
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange