Nginx virtual hosts, also known as server blocks, allow you to host multiple websites or applications on a single server by directing traffic based on the ports requested by clients.

Setting it up

This method is tested in Debian 12.

The config file we need to edit is located at /etc/nginx/sites-available/default.

Alternatively, you can create a new config file to set up your virtual hosts, but make sure to tell Nginx the location and name of the new file by editing /etc/nginx/nginx.conf.

By default, Nginx has configured 1 virtual host, listening on port 80. Its index directory is /var/www/html. There it will look for files called index, index.html, index.htm, or index.nginx-debian.html. Of course, you can change the filenames it is looking for, or the whole path.

This is what the default file looks like:

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;
    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
        try_files $uri $uri/ =404;
    }
}

Adding Another Virtual Host

We can now add another virtual host to it. In this example, it will listen on port 8080 and have /var/www/html2/vhost1index.html as its index file.

This is what the file would look like with this example added:

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;
    index index.html;

    server_name _;

    location / {
        try_files $uri $uri/ =404;
    }
}

server {
    listen 8080;
    listen [::]:8080;

    root /var/www/html2;
    index vhost1index.html;

    server_name vhost1;

    location / {
        try_files $uri $uri/ =404;
    }
}

Testing and Restarting Nginx

Now it's time to test our configuration by running the following command in our terminal:

# nginx -t

When no issues were found, restart Nginx by running:

# systemctl restart nginx

Result

Now our server hosts 2 different websites on different ports:

Port Server Directory
80 default_server /var/www/html/index.html
8080 vhost1 /var/www/html2/vhost1index.html