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

    UseCanonicalName    Off
    VirtualDocumentRoot /var/www/%0


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/ ->
/var/www/ ->

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;
    root /var/www/;
    # 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: