Running several websites on one nginx

The problem. One machine, several websites, one nginx. Each site has its own files in its own directory, and nginx has to serve the right files for the right site without the sites colliding. The whole trick is making nginx point at each site's directory explicitly. Miss that, and a site either shows nothing or shows the wrong content.

The fix.

Give every site its own server block, in its own file under /etc/nginx/sites-available/, then symlink each one into /etc/nginx/sites-enabled/. A single site's block looks like this:

server {
    listen 8008;
    listen [::]:8008;
    root /var/www/html/hybridrobotix_net/public;
    index index.html;
    server_name _;
    location / {
        try_files $uri $uri/ =404;
    }
}

Two lines carry the weight. listen sets the port, and root points at that exact site's built directory. When the sites do not have separate domain names yet, the port is what keeps them apart: each site gets a different listen port.

On a test box this is not optional. Every site shares the one hostname, so every site must run on its own separate port, and the port becomes the address. I reach any site on the test machine at:

hybx-test.local:<port>

This very site sits on port 8008, so it answers at hybx-test.local:8008. When the sites do have real domains, server_name does the separating instead and they can share a port. Either way, every site needs its own block with its own root, or nginx has nothing to serve for it.

Enable a site by symlinking its file, then test the configuration before you reload, so a single typo never takes the whole server down:

sudo ln -sf /etc/nginx/sites-available/hybridrobotix_net /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

Repeat the block for every site, each with its own port and its own root. That is the entire multi site configuration: one server, many blocks, each one aimed at exactly one directory.