Managing multiple hosts in NGINX

If you’re developing on a Vagrant controlled virtual machine you’ll probably want to run multiple projects from the same machine there are a couple of options. Here’s my full NGINX config:

server {
    listen          80;
    server_name     127.0.0.1;
    root            /var/www/html/my-project/public;
    index           index.php index.html index.htm;

    client_max_body_size 500M;

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

    location ~ \.htaccess {
        deny all;
    }

    location ~ \.php$ {
            try_files $uri =404;
            fastcgi_index index.php;
            fastcgi_pass  127.0.0.1:9000;
            include       fastcgi_params;
            fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
            fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
    }

    location ~ /\.ht {
        deny  all;
    }

    location ~ /\.svn {
        deny  all;
    }

    error_page 404 /404.html;
        location = /40x.html {
    }

    error_page 500 502 503 504 /50x.html;
        location = /50x.html {
    }
}

If we go directly to the IP address for this Vagrant box, we’ll end up at the site my first config is pointing to. When we come to add another config, we’re going to end up with a clash in server names, as they’ll share the same IP address, which config gets loaded first will resolve to that IP and port number.

We can change that port number to allow us to use port numbers to point to individual configurations:

listen          8444;
server_name     127.0.0.1;

We can now access this configuration by adding the port number to the URL of your Vagrant box: http://192.168.20.30:8444

Alternatively we can use the server_name parameter to assign a name to a configuration:

listen          80;
server_name     my-project.test;

To use hostnames to resolve to our project directory, we need to add an extra line to our host machine’s hosts file. In macOS that’s in: /etc/hosts add the following line:

192.168.20.30 my-project.test

We can now hit our new project with the url http://my-project.test.

Leave a Reply

Your email address will not be published. Required fields are marked *