
How it works...
We'll go through this one in sections. Magento is different from many flat file / single root directory structures, so it requires some slight changes compared to a basic PHP site.
set $MAGE_ROOT /var/www/html;
This sets a variable we can easily reference and it means there's only one place we need to update if we move the files:
root $MAGE_ROOT/pub/;
All of the main website files sit in the pub subdirectory. This is commonly overlooked when uploading the files to a shared hosting platform such as CPanel or Plesk. Ensure that the main root directive points to the pub folder, not just the directory of the Magento files. The root directive is therefore pointed at the pub folder with the preceding configuration line.
Conversely, the setup and update URLs need to have a separate root directive to ensure they also point to the correct location:
location (/setup|/upgrade) { root $MAGE_ROOT;
}
This sets the root back to the default directory, which sits outside the pub directory. The easiest way to look at it is to view the setup and upgrade sites as separate websites with their own separate structure. This is why the directive block also has the following:
location ~ ^/(setup|update)/index.php { fastcgi_pass unix:/var/run/php7.0-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME
$document_root$fastcgi_script_name; include fastcgi_params; }
We only allow access to index.php within the setup/update directories, and then deny access to any nonpub file:
location ~ ^/(setup|update)/(?!pub/). { deny all; }
This will give a 403 error if a malicious user or script attempts to access files outside the pub directory.
It also ensures that all requests come from the same frame, which will prevent clickjacking:
add_header X-Frame-Options SAMEORIGIN;
The static and media sections are both fairly similar in how they operate. Headers are set for caching (explained in more detail in Chapter 7, Reverse Proxy) and the calls are wrapped through a PHP function (static.php or get.php) to allow Magento to perform tasks such as file merging and minification. It can result in a slightly slower first hit, but as it caches the result each subsequent request should be very fast.