Magento2
multistore

Here you learn how you can setup multiple stores and multiple websites in Magento 2.
we are having a different domain or sub-domain for the stores and websites.

Create/Add new stores and websites from Magento admin:

  1. Login to Magento admin panel
  2. Go to STORES -> All Stores
  3. Create Website
  4. Create Store
  5. And, then Create Store View

Assume that we have created the following Website/Store/Store view:

Website: base
Store: main_website_store
Store View: default

Website: base
Store: main_website_store
Store View: new

Website: wholesale_website
Store: wholesale_store
Store View: wholesale

This means that we have created 2 websites.

– One website is the base or main website which has two store views with code `default` and `new`.
– The other website is the wholesale website which has a single store view with code wholesale.

Here are the URLs that I want to use for my stores and website:

Default Store: example.com
New Store: new.example.com
Wholesale Website: wholesale.example.com

Link the URLs to the stores and website
To link the URLs to their respective stores and website, we can either add the code in the index.php file or in the .htaccess file.


Please note:
– You don’t need to update both files.
– You can either update .htaccess file or index.php file.
– Updating .htaccess file is recommended.

Adding code in .htaccess file
Add the following code at the end of the .htaccess file:

SetEnvIf Host .*new.example.com.* MAGE_RUN_CODE=new
SetEnvIf Host .*new.example.com.* MAGE_RUN_TYPE=store
 
SetEnvIf Host .*wholesale.example.com.* MAGE_RUN_CODE=wholesale_site
SetEnvIf Host .*wholesale.example.com.* MAGE_RUN_TYPE=website

Adding code in index.php file
By default, at the end of your index.php file, you will have the code something like this:

$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication(\Magento\Framework\App\Http::class);
$bootstrap->run($app);

We will update it like this:

switch($_SERVER['HTTP_HOST']) {
    case 'new.example.com':
        $mageRunCode = 'new';
        $mageRunType = 'store';
    break;
    case 'wholesale.example.com':
        $mageRunCode = 'wholesale_site';
        $mageRunType = 'website';
    break;
    default:
        $mageRunCode = 'base';
        $mageRunType = 'website';
}
$params = $_SERVER;
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE] = $mageRunCode;
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_TYPE] = $mageRunType;
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params);
 
/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication(\Magento\Framework\App\Http::class);
$bootstrap->run($app);

Hope this will helps you!