Tutorial of Installing and Managing Nginx on Ubuntu

Linux Topic

November 5, 2022 by Liosa F

Tutorial of Installing and Managing Nginx on Ubuntu

Nginx is an open-source web server that was developed with efficiency and concurrency in mind. As a web server that solves scalability problems and provides the best performance, it is trendy among the world’s web servers. It hosts some of the most famous and most visited websites on the Internet. Nginx’s event-driven architecture has been its distinguishing feature and the reason for its superiority over other competitors. Nginx has the best performance in load balancing, caching, and acting as a reverse proxy and is a flexible option that is used as a reverse proxy or web server.

Some Ubuntu users are looking for a tutorial to guide them in installing Nginx; For this reason, in this article, We will teach how to install and manage Nginx on Ubuntu 20.04 server, configure the firewall and configure server blocks to host multiple domains from one server.

prerequisites for installing Nginx

Before starting, you must configure a regular, non-root user account with sudo permission on your server. Optionally, you can register the domain name because you will need it in the final stages.

Additionally, you may want to specify your hostname, define the time zone, and set up SSH access.

If you have an account, you can start the Nginx installation process by logging in as a non-root user.

More importantly, to use Nginx on your server, you need to buy a suitable Linux VPS with sufficient resources and then install Nginx on your Ubuntu server by following the steps below.

Step 1: Install Nginx

Since Nginx can be found in Ubuntu’s default repositories, you can install Nginx from these repositories by entering the apt packaging system command.

In order to access the latest package list, it is best to update your local package directory and then install Nginx:

sudo apt update
sudo apt install nginx

After confirming the operation, Nginx and all dependencies required for Nginx installation will be installed on your server by apt.

Step 2: Configuring the firewall

Before testing Nginx, the firewall must be configured to allow access to the service. After installation, Nginx is registered in ufw as a service, which makes it easier to access Nginx. In Ubuntu, ufw is used as a front-end to manage firewall rules.

Type the following commands to see a list of application configurations that ufw is familiar with them and can perform those application configurations:

sudo ufw app list

As a result of this command, a list of program profiles will be displayed to you:

Output

Available applications:

  Nginx Full

  Nginx HTTP

  Nginx HTTPS

  OpenSSH

In the received output, you will see three profiles of Nginx Full, Nginx HTTP, and Nginx HTTPS, each of which is displayed for a function.

  • Nginx Full: Enabling this profile will include rules for port 443 (TLS/SSL encrypted traffic) and port 80 (regular, unencrypted web traffic) and will open both ports for you.
  • Nginx HTTP: This profile is used when you only want to open port 80 (regular, unencrypted web traffic).
  • Nginx HTTPS: This profile also only opens port 443.

We recommend enabling a profile that is the most detailed and restrictive and can allow configured traffic.

In this tutorial, we will open port 80 for system firewall settings and allow traffic on port 80. To activate port 80 using ufw, enter the following command:

sudo ufw allow 'Nginx HTTP'

To confirm the settings, type the following command:

sudo ufw status

Which HTTP traffic is allowed is displayed in the output:

Output

Status: active

To                         Action      From

--                         ------      ----

OpenSSH                    ALLOW       Anywhere                 

Nginx HTTP                 ALLOW       Anywhere                 

OpenSSH (v6)               ALLOW       Anywhere (v6)            

Nginx HTTP (v6)            ALLOW       Anywhere (v6)

Step 3: Checking the status of the web server

After completing the installation process, Nginx will be successfully started on the Ubuntu server, and the web server should already be configured and running. To make sure the Nginx service is active, you can check the status of the service using the following command:

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 Fri 2020-04-20 16:08:19 UTC; 3 days ago
    
         Docs: man:nginx(8)
    
     Main PID: 2369 (nginx)
    
        Tasks: 2 (limit: 1153)
    
       Memory: 3.5M
    
       CGroup: /system.slice/nginx.service
    
               ├─2369 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
    
               └─2380 nginx: worker process

After running the above command, you will see active (running), and you will notice that the Nginx service has been successfully activated by default, and as soon as your system starts working, the Nginx service will run automatically.

However, requesting the page directly from Nginx is the best way to check the Nginx service running status. By referring to your server’s IP address, you can access the default Nginx landing page to verify that Nginx is working correctly. Having the Ip address of your server, type it in the address bar of the browser:

http://your_server_ip

After entering the IP address of the Ubuntu server, the output should be as follows:

Installing and Managing Nginx on Ubuntu

By viewing this page, ensure the Nginx service is running correctly, and you can manage it.

Step 4: Managing the Nginx service

Now that you are enjoying the Nginx web server on the Ubuntu server, it is better to familiarize yourself with some basic administration commands.

When you want to stop the web server, enter the following command:

sudo systemctl stop nginx

While the Nginx service is stopped and you want to start it, use the following command:

sudo systemctl start nginx

If you are making configuration changes, Nginx has the ability to reload without disconnecting. For this purpose, enter the following command:

sudo systemctl reload nginx

To disable the automatic startup of the Nginx service when the server boots, run the following command:

sudo systemctl disable nginx

To re-enable the automatic start of Nginx service when the server boots, enter the following command:

sudo systemctl enable nginx

The commands that we provided are the basic commands for managing the Nginx web server. In the following, we will teach the possibility of setting up a website to host multiple domains through Nginx.

Step 5: Setting up Server Blocks

Server blocks, like virtual hosts in Apache, are used to encapsulate configuration information and host multiple domains from a single server running Nginx.

We put your_domain instead of your domain name in our commands, so you need to type your domain name instead of your_domain for configuration when entering your commands.

The Nginx server block, which is automatically enabled on Ubuntu, is configured to serve files outside the /var/www/html directory. But note that this feature works well for hosting one site, but it can be problematic to host more than one site.

Preferably, creating a new directory in /var/www for the site with our own domain name is a better way than trying to make changes in /var/www/html. You can consider /var/www/html as the default directory so that when the client’s request does not match other sites, the /var/www/html directory will serve its purpose and be served.

To create a directory for your domain name enter the following command, the -p flag is used to create the directory:

sudo mkdir -p /var/www/your_domain/html

Next, use the $USER environment variable to specify the owner of the directory:

sudo chown -R $USER:$USER /var/www/your_domain/html

Modifying web root permissions is mandatory if you have not changed the umask value that determines the default file permissions. To confirm your permissions are correct and allow the owner to read, write and execute files while only certain people have read and execute permissions, run the following command:

sudo chmod -R 755 /var/www/your_domain

Then, to create the index.html sample page using the nano editor or whatever editor you use, type the following command:

sudo nano /var/www/your_domain/html/index.html

Add the following HTML sample to the file:

/var/www/your_domain/html/index.html

<html>

<head>

<title>Welcome to your_domain!</title>

</head>

<body>

<h1>Success!  The your_domain server block is working!</h1>

</body>

</html>

Save your changes, and then press Ctrl+X to exit the file.

After you are prompted to save, press Y and then hit Enter.

Create a server block with the appropriate directives to enable Nginx to serve this content.

Instead of making changes to the default configuration file, We will create a new configuration file in /etc/nginx/sites-available/your_domain. So, to do this, run the following command:

sudo nano /etc/nginx/sites-available/your_domain

In the next step, paste it into the configuration block that you will see below. This configuration block has been updated for our new domain name and directory.

/etc/nginx/sites-available/your_domain

server {

listen 80;

listen [::]:80;

root /var/www/your_domain/html;

index index.html index.htm index.nginx-debian.html;

server_name your_domain www.your_domain;

location / {

try_files $uri $uri/ =404;

}

}

So we changed server_name to our domain name and root settings to our new directory.

Now link the file to the sites-enabled directory, which Nginx reads from when it starts, and enable the file through the following command:

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

It should be noted that Nginx can track the activation of server blocks by using symbolic links. Symbolic links are like creating a shortcut on the disk, which allows you to keep server blocks available in the list of sites if you want them to remain active. If you decide to remove them, you can delete the shortcut from the sites-enabled directory in the future.

Therefore, to respond to requests based on the rules and settings of listen and server_name, two Server blocks are configured as follows:

  1. your_domain: responsible for responding to your_domain and www.your_domain requests.
  2. Default: responds to requests that do not match other blocks on port 80.

You may run into hash bucket memory issues due to adding different server names, so you need to change a single variable in the /etc/nginx/nginx.conf file. To do this, open the file:

sudo nano /etc/nginx/nginx.conf

In the file, after finding the server_names_hash_bucket_size directive, remove the # symbol to uncomment the line.

In the nano editor, you can effortlessly search and find the desired words in the file by pressing the CTRL and w buttons simultaneously.

/etc/nginx/nginx.conf

...

http {

...

server_names_hash_bucket_size 64;

...

}

...

After applying the settings, save the file and exit.

Then, to be sure, check that you don’t encounter syntax errors in the Nginx files.

sudo nginx –t

After making sure that there are no syntax errors in any of the Nginx files, restart the Nginx application via the following command to apply your settings:

sudo systemctl restart nginx

In the output, your domain name should be displayed by Nginx.

Note: You can also check this issue by visiting http://your_domain, and you should get the following output by visiting http://your_domain.

 Installing Nginx on Ubuntu

Step 6: Getting to know important Nginx directories and files

In this section, we want to talk about important Nginx directories and files.

content

directorydescription
/var/www/html:Web content, including the default Nginx page, is served from the /var/www/html directory, which can be adjusted by making changes to the Nginx configuration files.

Server configuration

directorydescription
/etc/nginxas the configuration directory that includes all the configuration files.
/etc/nginx/nginx.confit is the main Nginx configuration file. The desired changes must be made on this file to make general changes to Nginx.
/etc/nginx/sites-available/Nginx server block files are stored in this directory. Nginx does not use configuration files in this directory unless they are linked to the /etc/nginx/sites-enabled directory. All server block configurations are completed in this directory and then linked to another directory to be activated.
/etc/nginx/sites-enabled/This directory stores the enabled server blocks per site. In this directory, the files are a shortcut to the /etc/nginx/sites-available/ file and are created by linking to the configuration files in the available sites directory.
/etc/nginx/snippetsThis directory contains configuration pieces and minor settings that enable various features for the web server. Having potentially repeatable configuration sections is a smart idea to convert back to snippets.

Server Logs

directorydescription
/var/log/nginx/access.logAll web server requests are saved in the log file. Unless you have changed Nginx settings yourself.
var/log/nginx/error.log/All Nginx errors are stored in this directory.

FAQ

Nginx is an open-source web server that is designed for stability and performance improvement and is used for web serving, reverse proxying, caching, load balancing, and media streaming.

You can restart or stop the Nginx service by entering the systemctl command.

Restarting is when you want to make changes to ports or interfaces that are applied by reloading the new Nginx configuration. New worker processes are enabled by disabling old worker processes in the new configuration.

Summary

After successfully setting up your Nginx web server, you now have various options for the content you want to serve and the technologies you want to use to provide an enjoyable experience. For you, A new door will be opened to step into your development and progress path using Nginx features.

Our goal in this article is to teach how to install Nginx on the Ubuntu server and how to manage it, as well as get familiar with Nginx. We hope we have been able to explain it in the best possible way. If you encounter a problem in any part, share your question with us in the comments section so that we can guide you as soon as possible.

 

​ ​ ​ ​

About the Author Liosa F

Love, life, peace and technology are all for the wise man

Leave a Reply

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