How to set up Nginx server blocks (virtual hosts) on Ubuntu

Last updated on June 29, 2020

Nginx server blocks allow you to run multiple websites on a single server. Using this server block, you can specify the website document root, different SSL certificates for different sites, different security policies for different sites and reverse proxy configuration, and much more. Here the tutorial we explain the step by step instruction about how to set up Nginx server blocks on Ubuntu.


Before going to follow this tutorial you need to install Nginx and make sure it was running properly. Next, point your domains to your server and also make sure you have a non-root user account with sudo privileges

Create and set up domain root directories

Domain root directories where the website files stored and served by the server. We will use the following directory structure:

│   └── html
│   └── html
│   └── html

In the above, we create a root directory for all domains /var/www/ next, create a separate directory for each domain on that directory again create a new directory called html and stored the domain root files. Let's create a directory for our domain

sudo mkdir -p /var/www/

For testing, we create a new html file and place some html code in it.

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <meta charset="utf-8">
    <title>Welcome to</title>
    <h1>Success! home page!</h1>

Create a server block

By default on Ubuntu, Nginx server blocks configuration files are stored in /etc/nginx/sites-available directory, and the symbolic links to the /etc/nginx/sites-enabled/ directory.

Open the editor (in our case we choice nano editor) and create the following server block file:

sudo nano /etc/nginx/sites-available/
server {
    listen 80;
    listen [::]:80;

    root /var/www/;

    index index.html;


    access_log /var/log/nginx/;
    error_log /var/log/nginx/;

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

Enable the server block

To enable the new server block file, create a symbolic link from the file to the sites-enabled directory, which is read by Nginx during startup:

sudo ln -s /etc/nginx/sites-available/ /etc/nginx/sites-enabled/

Test Nginx configuration

To test the Nginx configuration by entering the below command:

sudo nginx -t

If there are no errors, the output will look like this:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Now, we are ready to restart Nginx to enable your changes. You can do that by typing:

sudo systemctl restart nginx

Test Nginx server block

Now, you should test that your server blocks are functioning correctly. You can do that by visiting the domain in your web browser:


Congratulation, Nginx server block to host multiple domains on a single Ubuntu server. You can host another domain by repeating the above steps. If you face any issues feel free to comment below we will assist you shortly.