How to set blocks (virtual hosts) on Nginx

How to set a block, i.e. a virtual hosts with Nginx :

Create the website folder :

sudo mkdir -p /var/www/example.com/html

Give the permissions to the folder :

sudo chown -R $USER:$USER /var/www/example.com/html
sudo chmod -R 755 /var/www

Create a html file :

nano /var/www/example.com/html/index.html

Add :


    
        Example website
    
    
        

Test page

Create the server block file :

sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/example.com
sudo nano /etc/nginx/sites-available/example.com

Modify it like that :

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

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

        server_name example.com www.example.com;

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

Enable the block :

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

Update the Nginx configuration file :

sudo nano /etc/nginx/nginx.conf
http {
    . . .

    server_names_hash_bucket_size 64;

    . . .
}

Test Nginx files :

sudo nginx -t

Restart Nginx :

sudo systemctl restart nginx

Test your website :

http://www.example.com

You should be redirected to the index page.