1)app/etc/frontend/events.xml :
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_predispatch">
<observer name="force_storecode_redirect" instance="Vendor\Module\Observer\ForceStorecodeRedirectObserver" shared="false" />
</event>
</config>
2)Observer/ForceStorecodeRedirectObserver.php
<?php
namespace Vendor\Module\Observer;
use Magento\Framework\Event\ObserverInterface;
class ForceStorecodeRedirectObserver implements ObserverInterface
{
protected $storeManager;
protected $url;
/** @var string $defaultStorecode */
protected $defaultStorecode = 'es';
/** @var array $storeCodes - array of existing storecodes*/
protected $storeCodes = [];
public function __construct(
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\UrlInterface $url
) {
$this->storeManager = $storeManager;
$this->url = $url;
$this->storeCodes = array_keys($this->storeManager->getStores(false, true));
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$urlParts = parse_url($this->url->getCurrentUrl());
$path = $urlParts['path'];
// get storecode from URL
$urlCode = trim(substr($path, 0, 4), '/');
// If path does not already contain an existing storecode
if (!in_array($urlCode, $this->storeCodes)) {
$path = ltrim($path, '/');
if ($path == 'en') {
$path = '';
}
// Redirect to URL including storecode
header("HTTP/1.1 301 Moved Permanently");
header("Location: " . $this->storeManager->getStore()->getBaseUrl() . $path);
exit();
}
}
}
de.company.com
for De store