7.09.16

Drupal 8 in a subdirectory with nginx

Assuming this nginx configuration as a starting point:

root /var/www/example.org/web;

location / {
  try_files $uri @rewrite;
}

location @rewrite {
  rewrite ^ /index.php;
}

You can configure your Drupal 8 instance to run in a subdirectory of the site with two simple steps.

In this example we change the instance’s base url from http://example.org/ to http://example.org/subdir/.

1. Change nginx configuration

Replace the ‘location /’ block with this:

location ~ /subdir/(.*) {
  try_files /$1 @rewrite;
}

2. Change Drupal settings.php

Add the following to your settings.php (or settings.X.php):

if(isset($GLOBALS['request'])) {
  $scriptName = $GLOBALS['request']->server->get('SCRIPT_NAME');
  $scriptName = preg_match('#^/subdir/#', $scriptName) ? : "/subdir$scriptName";
  $GLOBALS['request']->server->set('SCRIPT_NAME', $scriptName);
}

… and that’s it!

Hopefully there will be a cleaner way of doing this in the future…

Tested with Drupal 8.1.6.

Tags: , , | Posted in Uncategorized