Magento 2 – Run Multistore from Pub Directory

magento2multi-website

I scanned my site from the New Magento Security Tool available from magento partner portal.

The report showed me a vulnerability issue

Your Web server is configured to run Magento from %MAGENTO_ROOT% directory.
It is recommended to set %MAGENTO_ROOT%/pub as a Web server root directory.

The Magento installation is a multi-website with let's say 4 websites. When I set for example the document root of website 3 to /foo/bar/domain.website3/public/pub and after that navigate to the domain of website 3. Website 1 is shown, because the index.php which gets loaded is in the pub directory of the magento root installation. That means every domain will show the same website, because the index.php in the pub directory is static.

How can I setup my multi-website installation to use the pub directory as DocumentRoot?

Best Answer

To run Magento with multiple storeviews or websites without using the index.php hack you could configure this in your server software. Magento has documentation on this for both nginx (docs) and apache (docs)

(Update) MAGE_RUN_TYPE is what you want to call upon. Like a Magento website, or a store within a website. MAGE_RUN_CODE is the code belonging to that particular store view or website. (docs)

Nginx example (domains)

map $http_host $MAGE_RUN_CODE {
   default default;
   .example.com default;
   .example.fr french_store;
}

map $http_host $MAGE_RUN_TYPE {
   default store;
   .example.com store;
   .example.fr website;
}

Nginx example (storecode in url)

map $http_host $MAGE_RUN_CODE {
   default default;
   ~^/en/ default;
   ~^/fr/ french_store;
}

map $http_host $MAGE_RUN_TYPE {
   default store;
   ~^/en/ store;
   ~^/fr/ website;
}

Apache example (domains)

<VirtualHost *:80>
    ServerName          example.com
    ServerAlias         "www.example.com"
    DocumentRoot        /var/www/html/magento2/pub/
    SetEnv MAGE_RUN_CODE "default"
    SetEnv MAGE_RUN_TYPE "store"
</VirtualHost>

<VirtualHost *:80>
    ServerName          example.fr
    ServerAlias         "www.example.fr"
    DocumentRoot        /var/www/html/magento2/pub/
    SetEnv MAGE_RUN_CODE "french_store"
    SetEnv MAGE_RUN_TYPE "website"
</VirtualHost>
Related Topic