How to Configure Nginx Server Blocks on Ubuntu 18.04

Nginx Server Blocks allows you to run more than one website on a single machine. With Server Blocks, you can specify the site document root (the directory which contains the website files), create a separate security policy for each site, use different SSL certificates for each site and much more.

In this article, we’ll provide a step by step instructions about how to set up Nginx server blocks (similar to Apache Virtual Hosts) on Ubuntu 18.04.

Step 1) Create non-root user with sudo privileges configured

  1. Logging in as root
  2. Creating a new user
    # adduser bobby
  3. Granting Administrative Privileges
    To add these privileges to our new user, we need to add the new user to the sudo group. By default, on Ubuntu 18.04, users who belong to the sudo group are allowed to use the sudo command.

    # usermod -aG sudo bobby

Step 2) Install Nginx and Configure the firewall

Nginx packages are available in Ubuntu default software repositories. The installation is pretty straightforward, just type the following commands:

$ sudo apt-get update
$ sudo apt-get install nginx

Once the installation is completed, check the service status by type the following command :

$ sudo systemctl status nginx
output
   nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
     Active: active (running) since Wed 2018-07-25 13:14:45 UTC; 59s ago
       Docs: man:nginx(8)
    Process: 2756 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SU
    Process: 2747 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, st
   Main PID: 2762 (nginx)
      Tasks: 2 (limit: 1112)
     CGroup: /system.slice/nginx.service
             ├─2762 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
             └─2764 nginx: worker process

To know the Nginx version type the following command :

$ sudo nginx -V
output
nginx version: nginx/1.14.0 (Ubuntu)
built with OpenSSL 1.1.0g  2 Nov 2017

Our Ubuntu 18.04 server is protected by a firewall, So we’ll need to open HTTP (80) and HTTPS (443) ports.
By default Ubuntu 18.04 comes with a firewall configuration tool called UFW (Uncomplicated Firewall), So we can open the necessary ports with the following command:

Note: Nginx Full: This profile opens both port 80 (normal, unencrypted web traffic) and port 443 (TLS/SSL encrypted traffic)
$ sudo ufw allow 'Nginx Full'

We enable the ufw:

$ sudo ufw enable

We can verify the change with:

$ sudo ufw status
output
  Status: active

  To                         Action      From
  --                         ------      ----
  Nginx Full                 ALLOW       Anywhere
  Nginx Full (v6)            ALLOW       Anywhere (v6)

Now we can open http://server_domain_or_IP in our browser, and we should be able to see the default Nginx landing page as shown below:

nginx-screenshot

Step 3) Create the Directory Structure

Document root is the directory where the website files for a domain name are stored and served in response to requests. We can set the document root to any location we want but in this article we will use the following directory structure:

/var/www/
├── domain1.com
│   └── images
│   └── index.html
│   └── style.css
├── domain2.net
│   └── images
│   └── index.html
│   └── style.css

Basically we will create a separate directory for each domain we want to host on our server inside the /var/www directory.

Let’s create the root directory for our domains:

$ sudo mkdir -p /var/www/domain1.com

For testing purposes we will create an index.html, style.css files and images directory inside the domain’s document root directory.

$ cd /var/www/domain1.com/
/var/www/domain1.com$ sudo mkdir images index.html style.css

Open our editor and create the demo file:

  

/var/www/domain1.com/index.html

<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Welcome to domain1.com</title> <link rel="stylesheet" href="style.css"/> </head> <body> <h1 style="color:green;text-align:center;">Success! domain1.com home page!</h1> </body> </html>

In this article, we are running the commands as sudo user and the newly created files and directories are owned by the root user.

To avoid any permission issues we can change the ownership of the domain document root directory to the Nginx user (www-data):

$ sudo chown -R www-data: /var/www/domain1.com

we will do the same procedures to the domain2.net

Step 4) Create Nginx Server Block Files for Each Domain

Now that we have the content we wish to serve, we need to actually create the server blocks that will tell Nginx how to do this.

By default, Nginx contains one server block called dfault which we can use as a template for our own configurations. We will begin by designing our first domain's server block, which we will then copy over for our second domain and make the necessary modifications.

1) Create the First Nginx Server Block File

As mentioned above, we will create our first server block config file by copying over the default file:

$ sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/domain1.com

Now, open the new file you created in your text editor with sudo privileges:

$ sudo nano /etc/nginx/sites-available/domain1.com

After editing the file, it will look similar to this:

/etc/nginx/sites-available/domain1.com

server { listen 80; listen [::]:80; root /var/www/domain1.com; index index.html index.htm index.nginx-debian.html; server_name domain1.com www.domain1.com; location / { try_files $uri $uri/ =404; } }

That is all we need for a basic configuration. Save and close the file to exit Ctrl + x.

2) Create the Second Nginx Server Block File

Now that we have our frist nginx server block configuration, we can use that as a basis for our second file. Copy it over to create a new file:

$ sudo cp /etc/nginx/sites-available/domain1.com /etc/nginx/sites-available/domain2.net

Open the new file with sudo privileges in your editor:

$ sudo nano /etc/nginx/sites-available/domain2.net

Adjust the root directive to point to our second domain's document root and adjust the server_name to match your second site's domain name (make sure to include any aliases).

When you are finished, our file will likely look something like this:

/etc/nginx/sites-available/domain2.net

server { listen 80; listen [::]:80; root /var/www/domain2.net; index index.html index.htm index.nginx-debian.html; server_name domain2.net www.domain2.net; location / { try_files $uri $uri/ =404; } }

Save and close the file to exit Ctrl + x.

Step 5) Enable our Nginx Server Blocks and Restart Nginx

Now that we have our server block files, we need to enable them. We can do this by creating symbolic links from these files to the sites-enabled directory, which Nginx reads from during startup.

We can create these links by typing:

$ sudo ln -s /etc/nginx/sites-available/domain1.com /etc/nginx/sites-enabled/
$ sudo ln -s /etc/nginx/sites-available/domain2.net /etc/nginx/sites-enabled/

These files are now in the enabled directory, We now have three server blocks enabled:

  1. domain1.com: Will respond to requests for domain1.com and www.domain1.com
  2. domain2.net: Will respond to requests for domain2.net and www.domain2.net
  3. default: Will respond to any requests on port 80 that do not match the other two blocks.

In order to avoid a possible hash bucket memory problem that can arise from adding additional server names, we will go ahead and adjust a single value within our /etc/nginx/nginx.conf file. Open the file now:

$ sudo nano /etc/nginx/nginx.conf

Within the file, find the server_names_hash_bucket_size directive. Remove the # symbol to uncomment the line:

/etc/nginx/nginx.conf

http { . . . server_names_hash_bucket_size 64; . . . }

Save and close the file when you are finished.

Next, test to make sure that there are no syntax errors in any of our Nginx files:

$ sudo nginx -t

If no problems were found, restart Nginx to enable our changes:

$ sudo systemctl restart nginx

Nginx should now be serving both of our domain names.

Step 6) Go To Our Web Sites

Now that we are all set up, we should test that our server blocks are functioning correctly. We can do that by visiting the domains in our web browser:

http://domain1.com

You should see a page that looks like this:
domain1
If you visit your second domain name, you should see a slightly different site:

http://domain2.net

domain2Read Also :

If both of these sites work, we have successfully configured two independent server blocks with Nginx.

Ahmed Abdalhamid 8:55 am

About Ahmed Abdalhamid

Technical Support Engineer experienced in Linux servers administration of production environments. Exploring DevOps culture and tools. Interested in containerization and open source monitoring tools.

Author Archive Page

Have anything to say?

Your email address will not be published. Required fields are marked *

All comments are subject to moderation.