How to run Magento 2 from a sub-directory

Imagine you need to run a Magento 2 installation from a sub-directory, using Nginx, but you don’t have ownership of the main site, just the sub-directory.

So we are not talking here about store view codes, redirect loops etc, we are talking about this:

Server 1 : www.website.domain
/shop/ -> IP Server 2
Server 2 : www.website.domain/shop/

The problem

Magento 2 has differences in terms of application structure and directories with Magento 1. (see image below)

How to run Magento 2 from a subdirectory. Magento version comparison
How to run Magento 2 from a subdirectory. Magento version comparison

The most important difference here is the endpoint. While in Magento 1 the endpoint is the index file of the Magento installation, “[magento]/index.php”, in Magento 2, the endpoint is inside the pub folder, “/[magento]/pub/index.php”.

Therefore all request for each store-view will go through this folder.

Create Subfolders

For each Base URL you have to add a sub-folder at the end, so if you need to have www.website.domain/shop You will need to create :

mkdir ~/[magento]/pub/shop

Create Symlinks

Then you need to create symlinks inside the sub-folder just created to the static content folders, like ‘media’, ‘static’… This is necessary because Magento 2 will go to gather this information inside the reference given by the endpoint, that is inside the “pub/shop” folder.

For example:

ln -s ../media media
ln -s ../static static

For the index.php, instead of symlink. You need to copy it and modify the relative path for the app/bootstrap script. Like follows:

Change:

require realpath(DIR) . ‘/../app/bootstrap.php’;

To:

require realpath(DIR) . ‘/../../app/bootstrap.php’;

Nginx Configuration

And finally, make sure that the entry point of the Nginx file points to the correct folder.

location /shop/ {
    index index.php 
    try_files $uri $uri/ /shop/index.php?$args;
}

Did you face this problem? How did you solve it? Please comment below! 🙂

5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x