Setup Nginx Server Blocks (Part 1)

AiroServer's Blog

Based on our previous posts, now you know a lot about web servers and especially about Linux web servers. We’ve explained about LiteSpeed, Apache, and Nginx Web Server and compared them. We said it multiple times that although Nginx doesn’t have a GUI but it’s amazing for handling more than one domain. To handle multiple domains, first you need to setup server blocks. In this post, we’re going to show you how you can do that.

So, installing Nginx and configuring its firewall, you need to setup server blocks. We think that even if you want to handle one domain with this, it’s a good idea to setup the server block to make adding other domains easier in the future.

Making Directories

In this post, we are going to use these two to setup server blocks and make new directories:

  • mytest1.com
  • mytest2.com

The first step is to create two directories for two domains:

sudo mkdir -p /var/www/mytest1.com/public_html
sudo mkdir -p /var/www/mytest2.com/public_html

If you want the files to be editable by users other than the root, use these commands:

sudo chown -R $(whoami):$(whoami) /var/www/mytest1.com/public_html
sudo chown -R $(whoami):$(whoami) /var/www/mytest2.com/public_html

Create a text page

let’s create an index.html page for each domain:

sudo echo "Welcome to mytest1.com!" > /var/www/mytest1.com/public_html/index.html
sudo echo "Welcome to mytest2.com!" > /var/www/mytest2.com/public_html/index.html

Setup the first server block

There is a default server block in this path:

/etc/nginx/sites-available/default

Now we copy the file with a new name based on the domain:

sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/mytest1.com

Then we need to edit the file:

sudo nano /etc/nginx/sites-available/mytest1.com

Find the root /var/www/html in the mentioned file and replace it with the path of the directory you made earlier. For example: /var/www/mytest1.com/public_html

Edit file

Now find the server_name _;  line and change the domain name. (You can search for this line using Ctrl+W)

Save the changes and close the file. (Use Ctrl+X then Y to save changes)

Before going for the next step, let’s make sure the Nginx config file exists:

sudo nginx -t

You should see this as a result:

The first server block has been set up and in our next post, we’ll show you how to set up the second one. Make sure to check that post to finish the setup of the server blocks.

Hope you enjoyed this post if you did, you can visit our blog for more!

Find More Articles...

Whats New?

en_USEN