VirtualDocumentRoot with Nginx

VirtualDocumentRoot with Nginx

I recently upgraded our internal LEMP stack to use Nginx instead of Apache and one of the feature I missed was the VirtualDocumentRoot directive from a module called mod_vhost_alias to dynamically set the DocumentRoot like this:

<VirtualHost *:80>

  DocumentRoot  /var/www
  ServerName    example.com

  UseCanonicalName    Off
  VirtualDocumentRoot /var/www/%0

</VirtualHost>

This is very usefull for any local or staging environement where you don't want to create a seperate vhost everytime you need to setup a new project. Instead you just have to create a folder.

/var/www/example.com -> http://example.com
/var/www/127.0.0.1.xip.io -> http://127.0.0.1.xip.io

Now if you want to use this feature in Nginx you can simply to use the $host variable on the root directive and make sure this vhost is the default one.

server {

  listen 80 default_server;

  server_name _;
  root /var/www/$host;

}

The server_name can be anything but the default_server on the listen directive is important, specially if you want to use more than one vhost.

You can also overwrite this vhost like you usually do.

server {
  listen 80;
  server_name example.ngrok.io;
  root /var/www/example.com;
  #include fpm-laravel.conf;
}

If you want to take a closer look at how it works in a real setup you can check this Git repo: https://github.com/milhouse1337/vagrant-lemp

EOF