Installing and Managing Nginx on Ubuntu: A Complete Beginner Guide

Installing and Managing Nginx on Ubuntu involves adding the Nginx package, installing it with apt, and using commands to start, stop, and check the server status. This process helps users host websites on Ubuntu.

🤖AI Overview:

Installing and Managing Nginx on Ubuntu involves setting up the popular web server software and handling its ongoing configuration and maintenance. The main goal is to ensure Nginx runs efficiently and securely on Ubuntu systems. This process includes installation, starting or stopping the service, and updating configuration as needed. Understanding these steps helps keep websites hosted on Ubuntu stable and responsive.

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 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/snippets This 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.

Conclusion

Installing and Managing Nginx on Ubuntu is a fundamental skill for anyone starting with web servers. With step by step actions and focus on security and organization, you can serve websites and applications efficiently. I am confident you will find this process straightforward and rewarding. If you need additional support, OperaVPS is here to help you along the journey.

FAQ

To install Nginx on Ubuntu, you can use the built-in package manager. First, update your package lists with "sudo apt update", then run "sudo apt install nginx". After installation, you can start or stop the service with "sudo systemctl start nginx" or "sudo systemctl stop nginx".

Common Nginx commands on Ubuntu include:

- "sudo systemctl start nginx" to start the service

- "sudo systemctl stop nginx" to stop it

- "sudo systemctl restart nginx" to restart it

- "sudo systemctl reload nginx" to reload the configuration without downtime

You can verify the status of Nginx by running sudo systemctl status nginx. A message will indicate whether Nginx is active and running. You can also open your browser and visit your server’s IP address; if Nginx is running, you will see the default welcome page.

To configure Nginx, create or edit a configuration file in the /etc/nginx/sites-available directory. Define the server block with your domain name or IP address and the root path to your website files. After editing the configuration, reload Nginx with sudo systemctl reload nginx to apply changes.

Keeping your system and Nginx updated, using secure permissions, enabling the firewall, and configuring SSL with HTTPS are important security steps. You should also routinely check logs and restrict unnecessary access to configuration files.

For SSL and HTTPS, you can use a free certificate from Let’s Encrypt. Install Certbot with "sudo apt install certbot python3-certbot-nginx", then run "sudo certbot --nginx". Certbot will guide you through the steps to secure your site with HTTPS.

Nginx log files are located in the "/var/log/nginx/" directory. The "access.log" file shows visitor requests, and the "error.log" file contains messages about problems or issues. You can read them using commands like "less", "cat", or "tail" for real-time updates.

Check the error messages displayed in the terminal or in the "/var/log/nginx/error.log" file. Common issues include conflicts on port 80, incorrect configuration syntax, or permission problems. Make sure your settings match official Nginx guidelines to resolve errors quickly.

To upgrade Nginx, first update your package lists with sudo apt update, then use sudo apt upgrade nginx. If you need a specific newer version, you may need to add the official Nginx repository. Always back up your configuration files before upgrading.

Leave a Reply

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