Nginx can be installed as a prebuilt binary package or by compiling from source. Compiling from source allows for more customization options but it is also more complex.

Additionally, Nginx is available as Mainline and Stable versions. The mainline builds are the latest ones, but they also tend to be comparatively buggy as they include experimental modules.

In this tutorial I’ll show you how to install Nginx on Ubuntu 22.04 using different available methods and configure it.

Before you begin

If you are on a desktop edition of Ubuntu, simply open the terminal and begin the installation. However, if you’re installing on a server, start by logging in to the server using SSH.

ssh root@your_server_ip

… enter the password as requested

I advise against using the root account for administering your server. Instead create a new non-root user with sudo privileges with its own home directory using the useradd command.

Before installing Nginx, it’s important to make sure your Ubuntu installation is up to date. You can update your system by running the following commands:

sudo apt update && sudo apt upgrade -y

Installing Nginx on Ubuntu 22.04

Installing Nginx through the official Ubuntu package repository is easy. Just type the following commands

sudo apt install nginx -y

You can verify it’s running by entering

nginx -v

which will output the version of the newly installed Nginx

The default installation of Nginx will serve the ‘index.nginx-debian.html‘ file from the ‘/var/www/html/‘ directory. If the installation was successful, the contents of this file will be displayed when you access your server’s IP address in a web browser.

http://server_ip_address

Creating a new index.html file in /var/www/html will overwrite the default index.nginx-debian.html, allowing you to serve custom HTML when visiting the server’s IP address.

Use a text editor to create a new index.html file

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

and enter some html content

<html>
   <head>
    <title>Welcome to linuxstart.com</title>
   </head>
   <body>
      <h1>Hi. You’re on linuxstart.com</h1>
   </body>
</html>

save and exit nano with Ctrl + O then Ctrl + X

Your newly created file will override the default index.nginx-debian.html and will be displayed when you refresh the browser.

Installing Latest Version of Nginx on Ubuntu 22.04

Installing the package with the above steps is quick and simple, but it’s not usually up-to-date.

If you don’t want to follow this method you can skip this step

If you’d like to install the latest version, it would be better to install directly from the Nginx repo as shown below.

1.  First, install CURL, Nginx key archive, and other prerequisites with:  

sudo apt install curl gnupg2 ca-certificates lsb-release debian-archive-keyring -y

2.  Get a verified Nginx signing key with the following commands. Enter your password after the command runs.  

curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor \
    | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null

3.  Check the output to verify that it contains the full fingerprint

gpg --dry-run --quiet --import --import-options import-show /usr/share/keyrings/nginx-archive-keyring.gpg

573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62 as shown in the picture.

4.  As stated earlier, I’ll install the stable build. Set up the apt repository for this with:  

echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \
http://nginx.org/packages/mainline/ubuntu `lsb_release -cs` nginx" \
    | sudo tee /etc/apt/sources.list.d/nginx.list

5.  Now, configure repository pinning so that packages from the Nginx repo are preferred over Ubuntu-provided ones:  

echo -e "Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n" \
    | sudo tee /etc/apt/preferences.d/99nginx

6.  Finally, install the Nginx package with the following commands:  

sudo apt update && sudo apt install nginx -y

verify you have the installed the latest stable build with

nginx -v

Now restart your server and visit the IP to verify your installation.

http://server_ip_address

If you use this method to install the latest version of the nginx the file “index.html” will be served from the “/usr/share/nginx/html;” directory. You’ll also notice that the “sites-available” and “sites-enabled” directories are missing.

This is because the nginx by itself does not have this configuration in its package and the ubuntu maintained package does it for convention to mimic debian’s apache setup.

I’ll alter the necessary configuration and create the files to emulate the same setup.

Create the following directories

sudo mkdir /etc/nginx/{sites-available,sites-enabled}

edit the http block in the nginx.conf file

sudo nano /etc/nginx/nginx.conf

and after this line

include /etc/nginx/conf.d/*.conf;

add this

include /etc/nginx/sites-enabled/*;

Like so,

also move the default.conf file

sudo mv /etc/nginx/conf.d/default.conf /etc/nginx/sites-available/default.conf

and create symbolic link

sudo ln -s /etc/nginx/sites-available/default.conf /etc/nginx/sites-enabled/

restart the server and refresh the page

sudo systemctl restart nginx

Finally create the www folder which is not created by default following the second installation method

sudo mkdir /var/www 

Creating Your First Website

With that out of the way, It’s time to create your first website. Creating a website with Nginx involves creating a server block and linking it to a directory containing the website files. A server block is a configuration file that tells Nginx how to handle requests for a specific domain or subdomain.

I’ve used a domain called linuxstart.net for this tutorial. Going forward, you should replace linuxstart.net with your own domain name in all the steps.

To begin, create a directory to store your website’s content. This directory should be located within ‘/var/www/‘.

sudo mkdir -p /var/www/linuxstart

Create a basic index.html with a text editor. I’ll again use nano for this

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

Enter some html content

<html>
   <head>
    <title>Welcome to LinuxStart</title>
   </head>
   <body>
      <h1>Hi. You're on LinuxStart.com</h1>
   </body>
</html>

save and exit with Ctrl + O, then Ctrl + X

To create a server block, you can create a new file in the /etc/nginx/sites-available directory. For linuxstart, to create a server block for the domain linuxstart.net, you can create a new file called linuxstart.net in the /etc/nginx/sites-available directory.

sudo nano /etc/nginx/sites-available/linuxstart.net

add the following configuration

server {

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

}

This configuration tells Nginx to listen on port 80 for requests to the linuxstart.net domain, and serves files from the /var/www/linuxstart directory.

Once you have created the server block, you need to enable it by creating a symbolic link from the sites-available directory to the sites-enabled directory:

sudo ln -s /etc/nginx/sites-available/linuxstart.net /etc/nginx/sites-enabled/

You can then test the Nginx configuration by running the following command:

sudo nginx -t

This command will check the syntax of the configuration files and will alert you of any errors. Once you have confirmed that the configuration is correct, you can reload Nginx to apply the changes:

sudo systemctl reload nginx

Note: If you use an unusually long server name, or define a large number of server names, you may encounter hash buckets errors. In such cases, open the /etc/nginx/nginx.conf file and set the value of the

server_names_hash_bucket_size directive to 64

Managing and Monitoring Nginx Server

After you have successfully installed Nginx, It’s important to know how to manage it. The Nginx service is managed by systemd. You can start, stop and restart the Nginx service through the command using systemctl utility.

Here are some steps for managing and monitoring Nginx:

Stop, Start and Restart Nginx

sudo systemctl stop nginx
sudo systemctl start nginx
sudo systemctl restart nginx

Check the status of Nginx

sudo systemctl status nginx

You can reload the Nginx configuration without interrupting active connections by using the following command

sudo nginx -s reload

To disable the Nginx service, run:

sudo systemctl disable nginx

…to renable

sudo systemctl enable nginx

Configuring Firewall for Nginx

For security reasons,  it’s important to configure the firewall to allow incoming traffic to the Nginx server. By default, the Ubuntu firewall, known as ufw, blocks all incoming traffic. Therefore, you will need to open the necessary ports to allow incoming traffic to the Nginx server.

Here are the steps to configure firewall for Nginx:

Check the status of ufw using the following command:    

sudo ufw status

This command will display whether the firewall is active or inactive.  

If it’s inactive you can enable the firewall using the following command.

sudo ufw enable

Once it’s enabled you must have noticed you no longer are able to load the website anymore. For this you’ll have to allow incoming traffic to port 80 and 443 (if you are planning to use HTTPS) using the following commands:  

sudo ufw allow proto tcp from any to any port 80,443

Verify the firewall rules by running the following command:    

sudo ufw status numbered

Pointing a Domain to your website

If you have a registered domain name, you’ll need to point it to your NGINX server IP to access the site from the internet. Specifically, you’ll need to add a DNS A record with the target IP of the NGINX server from your domain name provider’s management console.

You can use curl –ipv4 icanhazip.com to get the server’s public IP address.

If you don’t have a registered domain name, you can simply edit the hosts file for testing purposes.

If you are on a windows machine, the hosts file is located at C:\Windows\System32\drivers\etc and /etc/hosts on a linux machine

Edit the hosts file with your favorite text editor and add the IP and domain separated by space, like so

192.168.10.64 linuxstart.net

Now, You should be able to access your website by navigating to

http://your_domain_name in your web browser.

Using Certbot to secure your website

If you visit your newly created website, you may notice a warning in the address bar of your browser indicating that the connection is not secure.

This means that your website does not have Transport Layer Security (TLS) enabled. Without proper security, your traffic can be intercepted by your Internet Service Provider (ISP) or other malicious actors, and the connection is vulnerable to Man in the Middle (MITM) attacks.

Securing a website with HTTPS requires a signed public-key certificate from a trusted Certificate Authority. Certbot communicates with Let’s Encrypt, a free and popular certificate issuer, to simplify this certification process.

So, Obtaining an SSL certificate from Let’s Encrypt can be done easily with Certbot . However, one thing to keep in mind is that you will need a live domain to get the certificate. This is because Let’s Encrypt’s servers need to be able to reach your server and validate your domain ownership by responding to a challenge request

Let’s start by installing certbot

1.  Add the repository, then update:

sudo add-apt-repository ppa:certbot/certbot
sudo apt update

2. Start by installing certbot with the following commands:

sudo apt install certbot python3-certbot-nginx -y

3.  Now, execute the following command to generate the certificates:  

sudo certbot --nginx

4.  Enter your email address and accept the terms of service.

5.  If Certbot lists your sites, specify them using numbers. Otherwise, enter the domain name manually with and without the www prefix (e.g., linuxstart.net www.linuxstart.net), and separate them with a space.

If you want to requests certificates for multiple domains, specify their names and separate them in the same manner

6. Restart Nginx for the changes to take effect and the SSL connection will now be fully functional.

Before you can access the site on HTTPs connection, you have to make sure nginx is listening on port 443, for this make the following changes on your configuration file.

sudo nano /etc/nginx/sites-available/linuxstart.net

and add listen 443 ssl; like so

server {

    listen 80;
    listen [::]:80;
    listen 443 ssl;
    server_name linuxstart.net www.linuxstart.net;
    ssl_certificate     www.linuxstart.net.crt;
    ssl_certificate_key www.linuxstart.net.key;
    root /var/www/linuxstart;
    index index.html index.htm index.nginx-debian.html;
    
    location / {
        try_files $uri $uri/ =404;
    }

}

After reloading the server you should be able to access https://your_domain.com

Managing Multiple Websites

If you need to host multiple websites on a single Nginx server, you can create multiple server blocks, one for each website. The process is similar to creating your first website, but you will need to create a separate server block and directory for each website.

Here are the steps to set up multiple websites on a single Nginx server:

1.  Create a new server block configuration file in the /etc/nginx/sites-available directory for each website using the following command:

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

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

2.  Add the appropriate configuration for each website in its respective server block file. The configuration should include the listening ports, root directory, index file, server name and location block.

3.  Create the root directories for each website and the corresponding index files:

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

sudo nano /var/www/linuxstart1.com/html/index.html

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

sudo nano /var/www/linuxstart2.com/html/index.html

4.  Create a symbolic link to each server block configuration file in the /etc/nginx/sites-enabled directory using the following command:

sudo ln -s /etc/nginx/sites-available/linuxstart1.com /etc/nginx/sites-enabled/

sudo ln -s /etc/nginx/sites-available/linuxstart2.com /etc/nginx/sites-enabled/

5.  Test the Nginx configuration file for syntax errors using the following command:

sudo nginx -t

6.  Restart Nginx to apply the changes:

sudo systemctl restart nginx

7.  Configure the DNS settings of your domains to point to your server’s IP address.

Updating and Maintaining Nginx

Regularly updating and maintaining Nginx is important to ensure that it’s running smoothly and providing the best performance for your users. You can update Nginx by running the following command:

sudo apt-get update && sudo apt-get upgrade nginx -y

Uninstalling Nginx on Ubuntu

If you want to completely uninstall NGINX

sudo apt purge nginx nginx-common nginx-core -y

to keep the nginx config files and remove the Nginx package only enter

sudo apt remove nginx nginx-common nginx-core -y

To delete any unwanted libs installed by Nginx run

sudo apt autoremove -y

File Ownership and Permissions

It’s important to set the correct file ownership and permissions for the website files and directories. By default, Nginx runs as the www-data user and group. You can set the correct file ownership and permissions by running the following command:

sudo chown -R www-data:www-data /var/www/linuxstart

This command sets the ownership of the /var/www/linuxstart directory and all of its contents to the www-data user and group.

Configuring and Optimizing Nginx

Finding the best configuration for your specific needs will require a lot of testing. I recommend changing one setting at a time, testing the performance impact and keeping or reverting it as you see fit.

Before starting, you should also backup the default config file with

sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.original

You’ll need to reload Nginx with sudo systemctl reload nginx to apply any changes made. Additionally, if you plan to make a lot of config changes, creating copies of the config file at various points is a good idea.

There are many settings and options that can be adjusted to configure and fine tune Nginx for performance, speed, and security.

 Some of the most important settings include:

  •   Adjusting the worker_processes and worker_connections settings    
  •   Enabling gzip compression    
  •   Adjusting the keepalive_timeout setting    
  •   Enabling server-side caching    

You can find more information on how to configure and optimize Nginx in the official Nginx documentation.

Testing and Troubleshooting Nginx

The final step is to verify that the setup process and configuration changes went well.

Testing and troubleshooting Nginx involves testing the configuration, websites, and logs, and using various tools for monitoring resource usage and identifying security issues. Some of the most important tools for testing and troubleshooting Nginx include:

  •   The Nginx access and error logs    
  •   The Nginx status module    
  •   The Nginx stub status module    
  •   Tools like top, and htop

Important Configuration Files and Directories

  1. /var/www/ – The standard document root directory where Nginx serves websites from.
  2. /etc/nginx/ – The Nginx config directory.
  3. /etc/nginx/nginx.conf – The main Nginx config file.
  4. /etc/nginx/conf.d/ – Directory for storing site-specific config files.
  5. /etc/nginx/sites-available and /etc/nginx/sites-enabled: These directories contain the configuration files for individual websites. The sites-available directory contains all the configurations for the websites hosted on the server, while the sites-enabled directory contains the configurations for the websites that are currently active. 
  6. /var/log/nginx/access.log – Log file for logging every request to your web server.
  7. /var/log/nginx/error.log – Log files for logging Nginx errors.
  8. /usr/sbin/nginx: the Nginx binary file, used to start and stop the Nginx server.    
Binod Bharati

CEO / Founder

Binod Bharati is a skilled entrepreneur and an SEO strategiest with over 20 years of proven success in the technology sector. He is renowned for his expertise in computer hardware, networking, and security, with a special affection for Linux systems. Backed by numerous certifications including CompTIA's Pentest+, CySA+, Security+, Linux+, Network+, and A+, his knowledge and passion for computers shine through his work.