1

I am running magento 2 in a VM on apache2.

I created a new store view for another language of our shop.

Main domain: company.com

Storeview subdomain: de.company.com

Problem:

If I go to "http://de.company.com" then I get redirected to http://company.com.


I deleted all cookies and flushed the magento cache.

2
  • 1
    Check magento secure and unsecure are set to de.company.com for De store
    – Amit Bera
    Jan 18 at 7:48
  • Yes, they are .
    – Black
    Jan 18 at 12:05

2 Answers 2

0

1)Go to Admin CMS Configuration->General->Web->Url Options and store settings like followings:

enter image description here

-1

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();
       }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.