Magento – Magento2: Remove Store Code URL only for default store

magento2store-viewurlurl-rewrite

I am developing a Magento 2 store with two store views, one for each language(English and Italian). I turned on the "Add Store Code to Urls" option from backend, so my URLs looks like:

http://mystore.com/en (English)
http://mystore.com/it (Italian)

What I would like to do now is to remove the store code from URL for the default store view, to obtain something like this:

http://mystore.com/ (English)
http://mystore.com/it (Italian)

In Magento 1.9 there a few extensions that do this. I need to find something (or develop) for Magento 2.

Anyone has some hints?

A good example of what I am searching for is this:
https://github.com/lalitmohann/magento-hide-default-store-code

Best Answer

I had the same requirement and was able to solve it easily with just one plugin for Magento\Store\Model\Store::isUseStoreInUrl method.

public function afterIsUseStoreInUrl(\Magento\Store\Model\Store $subject, $resultIsUseInUrl)
{
    if ($subject->getCode() != $subject::ADMIN_CODE && $subject->isDefault())
    {
        return $resultIsUseInUrl && $this->scopeConfig->getValue('web/url/use_store_in_default');
    }
    else
    {
        return $resultIsUseInUrl;
    }
}

I registered the plugin in global di.xml instead of frontend because the first time this method is called area has not yet been set so the plugin would not get executed.