how to install nginx on ubuntu 2204 a comprehensive guide 667073d4106a9 - Tip Code X
Operating System

How to Install Nginx on Ubuntu 22.04 A Comprehensive Guide

Nginx is one of the most popular web servers in the world, known for its high performance, stability, rich feature set, simple configuration, and low resource consumption. This comprehensive guide will walk you through the process of installing and configuring Nginx on Ubuntu 22.04, ensuring you have a robust and efficient web server up and running.

Step 1: Update Your System

How to Install Nginx on Ubuntu 22.04 A Comprehensive Guide

Before we begin the installation process, it’s crucial to ensure that your system is up to date. This helps prevent any potential conflicts and ensures you have the latest security patches.

Update Package Information

Run the following command to update your local package index:

Bash
sudo apt update

Upgrade Installed Packages

After updating the package information, upgrade all installed packages to their latest versions:

Bash
sudo apt upgrade -y

Step 2: Install Nginx on Ubuntu 22.04

How to Install Nginx on Ubuntu 22.04 A Comprehensive Guide

Now that your system is up to date, you’re ready to install Nginx. Ubuntu’s default repositories contain Nginx packages, making the installation process straightforward.

Install Nginx Package

To install Nginx, use the following command:

Bash
sudo apt install nginx -y

This command installs Nginx along with all required dependencies.

Verify Installation

After the installation is complete, you can verify that Nginx was installed correctly by checking its version:

Bash
nginx -v

You should see output similar to:

Bash
nginx version: nginx/1.18.0 (Ubuntu)

Step 3: Adjust the Firewall

If you have the UFW (Uncomplicated Firewall) enabled, you’ll need to allow traffic on port 80 (HTTP) and optionally on port 443 (HTTPS) to access your web server.

List Available Application Profiles

First, list the application profiles that ufw knows how to work with:

Bash
sudo ufw app list

You’ll receive a list of application profiles:

Bash
Available applications:
  Nginx Full
  Nginx HTTP
  Nginx HTTPS
  OpenSSH

Here’s what each profile means:

  • Nginx Full: This profile opens both port 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)

Allow HTTP Traffic

For now, it’s best to allow only HTTP traffic. You can do this by typing:

Bash
sudo ufw allow 'Nginx HTTP'

Verify the Change

You can verify the change by typing:

Bash
sudo ufw status

The output will indicate which HTTP traffic is allowed:

Bash
Status: active

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

Step 4: Check Your Web Server

At the end of the installation process, Ubuntu 22.04 starts Nginx. The web server should already be up and running.

Check with systemd

We can check with the systemd init system to make sure the service is running by typing:

Bash
systemctl status nginx

The output should be similar to the following:

Bash
 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 Tue 2024-06-10 16:08:19 UTC; 1 days ago
       Docs: man:nginx(8)
   Main PID: 2369 (nginx)
      Tasks: 2 (limit: 1153)
     Memory: 3.5M
        CPU: 6.032s
     CGroup: /system.slice/nginx.service
             ├─2369 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
             └─2380 nginx: worker process

This output shows that the installation was successful. However, the best way to test this is to actually request a page from Nginx.

Access Default Nginx Page

You can access the default Nginx landing page to confirm that the software is running properly through your IP address. If you do not know your server’s IP address, you can get it a couple of different ways from the command line.

Try typing this at your server’s command prompt:

Bash
ip addr show eth0 | grep inet | awk '' | sed 's//.*$//'

This will print out a few IP addresses. You can try each of them in your web browser to see if they work.

An alternative is using the icanhazip.com tool, which will give you your public IP address as received from a location on the internet:

Bash
curl -4 icanhazip.com

When you have your server’s IP address, enter it into your browser’s address bar:

Bash
http://your_server_ip

You should see the default Nginx landing page:

Nginx default page

If you see this page, your web server is now correctly installed and accessible through your firewall.

Step 5: Manage the Nginx Process

Now that you have your web server up and running, let’s review some basic management commands.

Stop Web Server

To stop your web server, type:

Bash
sudo systemctl stop nginx

Start Web Server

To start the web server when it is stopped, type:

Bash
sudo systemctl start nginx

Stop and Start the Service

To stop and then start the service again, type:

Bash
sudo systemctl restart nginx

Reload Configuration

If you are simply making configuration changes, Nginx can often reload without dropping connections. To do this, type:

Bash
sudo systemctl reload nginx

Disable Automatic Start at Boot

By default, Nginx is configured to start automatically when the server boots. If this is not the behavior you want, you can disable this behavior by typing:

Bash
sudo systemctl disable nginx

Re-enable Automatic Start at Boot

To re-enable the service to start up at boot, you can type:

Bash
sudo systemctl enable nginx

Now that you have learned the basic management commands, you’re ready to configure server blocks to host more than one domain on your server.

Step 6: Set Up Server Blocks (Recommended)

When using the Nginx web server, server blocks (similar to virtual hosts in Apache) can be used to encapsulate configuration details and host more than one domain from a single server. We will set up a domain called your_domain, but you should replace this with your own domain name.

Nginx on Ubuntu 22.04 has one server block enabled by default that is configured to serve documents out of a directory at /var/www/html. While this works well for a single site, it can become unwieldy if you are hosting multiple sites. Instead of modifying /var/www/html, let’s create a directory structure within /var/www for our your_domain site, leaving /var/www/html in place as the default directory to be served if a client request doesn’t match any other sites.

Create the Directory for your_domain

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

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

Assign Ownership

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

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

Set Permissions

The permissions of your web roots should be correct if you haven’t modified your umask value, which sets default file permissions. To ensure that your permissions are correct and allow the owner to read, write, and execute the files while granting only read and execute permissions to groups and others, you can input the following command:

Bash
sudo chmod -R 755 /varwww/your_domain

Create a Sample Page

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

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

Inside, add the following sample HTML:

Bash

    
        Welcome to Your_domain!
    
    
        Success! The your_domain server block is working!
    

Save and close the file.

Create a New Server Block

In order for Nginx to serve this content, it’s necessary to create a server block with the correct directives. Instead of modifying the default configuration file directly, let’s make a new one at /etc/nginx/sites-available/your_domain:

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

Paste in the following configuration block, which is similar to the default, but updated for our new directory and domain name:

Bash
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;
        }
}

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

Enable the File

Next, let’s enable the file by creating a link from it to the sites-enabled directory, which Nginx reads from during startup:

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

Avoid Hash Bucket Memory Problem

Next, let’s adjust a single value in the /etc/nginx/nginx.conf file. Open the file:

Bash
sudo nano /etc/nginx/nginx.conf

Find the server_names_hash_bucket_size directive. Remove the `

symbol to uncomment the line:

Bash
http {
    server_names_hash_bucket_size 64;
}

Save and close the file when you are finished.

Test Configuration and Restart Nginx

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

Bash
sudo nginx -t

If there aren’t any problems, restart Nginx to enable your changes:

Bash
sudo systemctl restart nginx

Nginx should now be serving your domain name. You can test this by navigating to http://your_domain, where you should see something like this:New Nginx Website

Step 7: Familiarize Yourself with Important Nginx Files and Directories

Now that you know how to manage the Nginx service itself, you should take a few minutes to familiarize yourself with a few important directories and files.

Content

  • /var/www/html: The actual web content, which by default only consists of the default Nginx page you saw earlier, is served out of the /var/www/html directory. This can be changed by altering Nginx configuration files.

Server Configuration

  • /etc/nginx: The Nginx configuration directory. All of the Nginx configuration files reside here.
  • /etc/nginx/nginxconf: The main Nginx configuration file. This can be modified to make changes to the Nginx global configuration.
  • /etc/nginx/sites-available/: The directory where per-site server blocks can be stored. Nginx will not use the configuration files found in this directory unless they are linked to the sites-enabled directory. Typically, all server block configuration is done in this directory, and then enabled by linking to the other directory.
  • /etc/nginx/sites-enabled/: The directory where enabled per-site server blocks are stored. Typically, these are created by linking to configuration files found in the sites-available directory.
  • /etc/nginx/snippets: This directory contains configuration fragments that can be included elsewhere in the Nginx configuration. Potentially repeatable configuration segments are good candidates for refactoring into snippets.

Server Logs

  • /var/log/nginx/access.log: Every request to your web server is recorded in this log file unless Nginx is configured to do otherwise.
  • /var/log/nginx/error.log: Any Nginx errors will be recorded in this log.

Conclusion

In this comprehensive guide, we have explored how to install and configure Nginx on an Ubuntu 22.04 server. Nginx is not only one of the most popular web servers in the world but also a lightweight and flexible choice for use as a web server or reverse proxy.

By following the steps outlined in this article, you should now have a fully functional Nginx server, ready to host your websites or applications. We covered everything from initial installation and firewall configuration to setting up server blocks and familiarizing ourselves with important Nginx files and directories.

Remember that web server security is an ongoing process, and it’s important to stay updated with the latest security practices. Consider implementing HTTPS for your websites, keeping your server and all installed software up to date, and regularly monitoring your server logs for any suspicious activity.

Nginx’s extensive documentation and active community make it an excellent choice for both beginners and experienced administrators. As you continue your journey with Nginx, don’t hesitate to dive deeper into its configuration options and advanced features to truly harness its power.

Happy hosting!

Leave a Reply

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

Back To Top
+