Setting up NGINX as a Web Server

NGINX is broad and can be used for different things, including setting it up as a web server, load balancer or reverse proxy. Learn how to set it up as a web server...

Hello “👋”

Welcome to another week, another opportunity to become a Great Backend Engineer.

Today’s issue is brought to you by MasteringBackend—a great resource for backend engineers: Next-level Backend Engineering training and Exclusive resources.

Before we get down to the business of today. Setting up NGINX as a Web Server.

I have a special announcement: You will love this one.

Masteringbackend is launching the beta version of its platform. We have been building intensively for the past five months, and today, we are finally pushing the beta version to you.

This platform will help you grow your backend engineering career and turn you into a great backend engineer.

It will house the following:

  1. Personal Backend Portfolio to showcase your skills

  2. Learn to build from Thousands of Real-world Projects

  3. Track your learnings and set schedules

  4. Follow expert-vetted roadmaps to learn backend engineering.

  5. Map courses to Backend Projects to help you master your skills

  6. Online coding challenges by experts to improve your skills

  7. Pick projects from different business domains to practice.

Sound interesting?

The beta version is out for testing, reviews, and feedback.

Sign up here and reply to this email if you find anything worth reporting or if there is more feedback to help us improve.

Now, back to the business of today.

In the previous edition, we discussed NGINX, how it works, and the different NGINX components. NGINX is one of the best open-source web servers, and it’s paramount to learn properly in backend engineering.

We will further discuss how to set up NGINX as a web server. This newsletter issue specifically focuses on setting up NGINX as a web server. NGINX is broad and can be used for different things, including setting it up as a web server, load balancer, or reverse proxy.

Different ways to set up Nginx depend on your operating system. We will use the Linux operating system for this demonstration while linking you to where you can learn how to install it in other operating systems.

To follow this guide, you should install Linux Ubuntu 18 or later on your machine or learn how to install it in Windows or MacOS.

Step 1 — Installing NGINX

Every Ubuntu installation comes with the apt packaging system; we will use that to install NGINX since it is available in the default repository. If you can’t find the apt packaging system, try installing it first.

Run the following commands to update the repository before installing NGINX:

sudo apt update
sudo apt install nginx

If you’re running this command for the first time, it might require you to authenticate with your system password.

If the command runs successfully, you should have NGINX installed on your device. Next, let’s look at configuring our firewall to allow NGINX.

Step 2 — Adjust Firewall Settings

Now that we have Nginx installed, we will adjust our firewall settings to allow access to the Nginx service.

Nginx makes this process very easy as it registers itself as a service ufw during installation, making it easier to allow Nginx access.

To allow access, use the following command below to list all the application configurations that ufw knows how to work with.

Use the command below to list out the options to select from:

sudo ufw app list

The list displays three different profiles available for Nginx:

  • Nginx Full: This profile opens both ports 80 (normal, unencrypted web traffic) and port 443 (TLS/SSL encrypted traffic)

  • Nginx HTTP: This profile opens only port 80 (normal, unencrypted web traffic)

  • Nginx HTTPS: This profile opens only port 443 (TLS/SSL encrypted traffic)

When working on a production-ready web server, it is recommended that you allow the most restrictive profile Nginx Full since you will allow traffic from HTTPS and maybe HTTP, too.

But you can only allow HTTP since you will work on your local machine and have no SSL.

Use the following command to select an option:

sudo ufw allow 'Nginx HTTP'

Once you’re done, you can verify your firewall settings using the status command:

sudo ufw status

You should receive a list of HTTP traffic allowed in the output, as shown in the screenshot below:

Output
Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere         
Nginx HTTP                 ALLOW       Anywhere                  
OpenSSH (v6)               ALLOW       Anywhere (v6)             
Nginx HTTP (v6)            ALLOW       Anywhere (v6)

Now that you’ve added the appropriate firewall rule, you can check that your web server is running and can serve content correctly.

Step 3 – Checking your Web Server

it’s important to check if the Nginx web server is started even though Ubuntu should automatically start the Nginx server during installation.

To check the status of our newly installed web server, type in the following command:

systemctl status nginx

This command will check the systemd init system to ensure the service is running.

Next, let’s try to render a simple page and see Nginx in action. To achieve this, we need to access the default Nginx landing page to tell us if Nginx is successful (If shown).

There are different ways to do this, but you can retrieve the NGINX IP address and use it to preview the landing page using the following commands to retrieve your default IP address:

ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\\/.*$//'

You can use the command below if the above doesn’t work for you due to uninstalled packages:

curl -4 icanhazip.com

This should give you an IP address. Visit the IP address in your web browser to preview the NGINX default landing page.

If you’re not successful, you might need to re-install Nginx or manage some of the processes using the commands listed below:

  1. To stop and restart the Nginx server

sudo systemctl restart nginx
  1. To stop the NGINX server from running:

sudo systemctl stop nginx
  1. To start the NGINX server:

sudo systemctl start nginx
  1. To reload the NGINX server after making changes to the configuration without stopping the server completely.

sudo systemctl reload nginx
  1. To disable NGINX from auto-starting when you boot your local machine, use the following command:

sudo systemctl disable nginx
  1. To enable NGINX to auto-start when you boot your local machine:

sudo systemctl enable nginx

Step 4 – Setting Up Server Blocks

Next, I will start setting up our server block, and I hope you have successfully installed and configured NGINX following the steps above.

Nginx comes with a default server block that is enabled by default, and that server block is what we used to preview the page above, which tells us that Nginx is working properly.

We can continue using that server block, but since Nginx supports multiple server blocks, creating multiple server blocks is a good practice and recommended.

What is a Server Block?

A server block is a subset of Nginx’s configuration that defines a virtual server that handles requests of a defined type. Administrators often configure multiple server blocks and decide which block should handle which connection based on the requested domain name, port, and IP address.

Here’s a screenshot showing the example of a server block:

server {
    listen 192.168.2.10;

    . . .

}

server {
    listen 80;
    server_name example.com;

    . . .

}

In Ubuntu 18.x, NGINX will have a default server block in this directory /var/www/html that works perfectly for a single site. However, we need to create multiple server blocks to host multiple sites.

In this guide, we will create an example server block that will serve as an example and should be replaced with your actual domain in your local machine or production server.

Create the directory for test.com as follows, using the -p flag to create any necessary parent directories:

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

Next, assign ownership of the directory with the $USER environment variable using the command below:

sudo chown -R $USER:$USER /var/www/test.com/html

The permissions of your web roots should be correct if you haven’t modified your umask value, however, you can make sure by typing the following command:

sudo chmod -R 755 /var/www/test.com

Next, create a sample index.html page using nano, vim or your favorite editor:

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

Inside, add the following sample HTML:

<html>
    <head>
        <title>Welcome to example.com!</title>
    </head>
    <body>
        <h1>Success! The example.com server block is working!</h1>
    </body>
</html>

Save and close the file when you are finished. If you used nano, you can exit by pressing CTRL + X then Y and ENTER.

For Nginx to serve this content, creating a server block with the correct directives is necessary. Instead of modifying the default configuration file directly, make a new one at /etc/nginx/sites-available/test.com:

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

Add the following configuration block, which is similar to the default but updated for your new directory and domain name:

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

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

        server_name test.com www.test.com;

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

Notice that we’ve updated the root configuration to the new directory and the server_name to the domain name.

Save and close the file when you are finished.

Next, enable the file by creating a symbolic link from it to the sites-enabled directory, which Nginx reads from during startup using the command below:

sudo ln -s /etc/nginx/sites-available/[your_domain] /etc/nginx/sites-enabled/

Two server blocks are now enabled and configured to respond to requests based on their listen and server_name directives:

  • test.com: Will respond to requests for test.com and www.test.com.

  • default: Will respond to any requests on port 80 that do not match the other two blocks.

Sometimes, Nginx can suffer from possible hash bucket memory problems from adding additional server names. It is necessary to adjust a single value in the /etc/nginx/nginx.conf file.

Open the file:

sudo nano /etc/nginx/nginx.conf

Find the server_names_hash_bucket_size directive and remove the # symbol to uncomment the line:

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

Save and close the file when you are finished, then test it using the following command:

sudo nginx -t

If there are no problems, then restart your server with the command below:

sudo systemctl restart nginx

Nginx should now be serving your domain name. You can test this by navigating to http://test.com.

That was a quick lesson on configuring NGINX as a Web Server. You can use NGINX for a lot more complex things.

I have already created an article exploring NGNIX and how to configure it as a load balancer, reverse proxy, etc., which will aid you in building scalable backend systems. Click here to learn.

That will be all for this one. See you on Saturday.

Don’t forget to Sign UP for the Beta version of Masteringbackend. It comes with unmatched benefits.

Weekly Backend Engineering Resources

Whenever you're ready

There are 4 ways I can help you become a great backend engineer:

1. The MB Platform: Join 1000+ backend engineers learning backend engineering on the MB platform. Build real-world backend projects, track your learnings and set schedules, learn from expert-vetted courses and roadmaps, and solve backend engineering tasks, exercises, and challenges.

2. The MB Academy:​ The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

3. MB Video-Based Courses: Join 1000+ backend engineers learning from our meticulously crafted courses designed to empower you with the knowledge and skills you need to excel in the world of backend development.

4. MB Text-Based Courses: Access 1000+ resources, including PDF guides, comprehensive reference materials, and text-based courses that cater to learners at various stages of their backend engineering journey.

I moved my newsletter from Substack to Beehiiv, and it's been an amazing journey. Start yours here.

Reply

or to participate.