Install NGINX On Ubuntu 22.04
Operating Systems

Install NGINX on Ubuntu 22.04

Learn how to install, configure, and optimize NGINX on Ubuntu 22.04. Deploy a high-performance web server and reverse proxy for modern, high-traffic applications.

Install NGINX on Ubuntu 22.04

Imagine having a well-developed website, but your web server can’t handle high traffic loads.

This can be problematic for high-traffic sites

NGINX, known for its performance, stability, and resource efficiency, can help you sort this out. It was originally developed to solve the C10K problem—the challenge of handling 10,000 concurrent connections.

Since then, it has evolved into a versatile solution that serves as both a high-performance web server and a sophisticated reverse proxy, load balancer, and HTTP cache.

Today, a well-configured NGINX installation serves as a backbone for hundreds of SMEs and corporate businesses’ operations.

In this tutorial, I will cover all you need to know about NGINX installation, configuration, security, and optimization. However, before all this, let us have a look at the prerequisites.

The Prerequisites

Before we move on, ensure you have the following:

  • You have an Ubuntu 22.04 system
  • A user with sudo/root privileges
  • Access to the terminal and a public IP address

Install NGINX on Ubuntu

Follow these steps to install NGINX on your server machine.

Step #1: Update System Package Repository

Start by updating the system package repository to ensure you have access to the latest version. This ensures system stability during installation.

# sudo apt update

sudo apt update

Step #2: Install NGINX

Once the package repository is updated, you can install NGINX from Ubuntu’s official repositories with the following command:

# sudo apt install nginx

sudo apt install nginx

Once installed, you can verify if it’s installed appropriately by checking the version installed.

# nginx -v

nginx -v

If the output displays the installed NGINX version, you have successfully installed it.

Adjust the Firewall for NGINX

Ubuntu 22.04 includes UFW as the default firewall management tool. Since NGINX serves web content, you need to configure the firewall to allow HTTP (port 80) and HTTPS (port 443) traffic.

Run the following command to allow HTTP and HTTPS traffic to NGINX:

# sudo ufw allow ‘Nginx Full’

sudo ufw allow 'Nginx Full’

This command instructs UFW to allow incoming connections on both standard HTTP and HTTPS ports. Once executed, run the following command to verify that the rules have been applied.

# sudo ufw status

sudo ufw status

You should see an active status.

Verify NGINX Web Server is Running

Once the installation and firewall configurations are successful, verify that the NGINX web server is running successfully by accessing the default welcome page.

Open your web browser and navigate to http://[your_server_ip].

Replace **[your_server_ip]**with your server’s public IP address.

Verify NGINX Web Server is Running

You should see the default NGINX welcome page. This confirms that NGINX is running and serving HTTP traffic.

If you have trouble accessing the Welcome page:

  • Check NGINX service status and restart it:

# sudo systemctl status nginx # sudo systemctl restart nginx

  • Check firewall rules:

# sudo ufw status verbose

Manage the NGINX Process with systemctl

systemctl is the primary command-line utility for controlling the systemd system and service manager. NGINX integrates with systemd to manage the web server service.

The following table summarizes some of the common systemctl commands for NGINX.

CommandPurpose
sudo systemctl start nginxStart the NGINX service
sudo systemctl stop nginxStop the NGINX service
sudo systemctl restart nginxRestart NGINX (useful after configuration changes)
sudo systemctl reload nginxReload the configuration without stopping the server
sudo systemctl enable nginxEnable NGINX on boot
sudo systemctl disable nginxDisable NGINX from starting automatically
sudo nginx -tTest NGINX configuration for errors
sudo journalctl -xeView detailed system logs (for debugging)

How to Set Up NGINX Server Blocks (Virtual Hosts)

NGINX server blocks, which are equivalent to Apache’s virtual hosts, allow users to host multiple websites or applications on a single NGINX server.

Create NGINX Server Blocks (Virtual Hosts)

Follow the steps below to set up NGINX server blocks.

Step #1: Create Directories for Website Content

Start by creating a dedicated folder for your website files and setting permissions to allow NGINX to serve and manage files securely.

For this demonstration, I will use the local path /var/www/example.com/htmlto save the files. You should name this folder appropriately for your project.

# sudo mkdir -p /var/www/example.com/html

# sudo chown -R www-data:www-data /var/www/example.com/html

# sudo chmod -R 755 /var/www/example.com

sudo chmod

Here,

  • mkdir -p: Creates the directory /var/www/example.com/html.
  • -p: Ensures that any parent directories (/var/www/example.com) are also created if they don’t already exist.
  • 755: The owner can read/write/execute, and the group and others can read/execute

Step #2: Add a Sample HTML Page

Now, create a simple test page to verify your server block configuration works.

# sudo nano /var/www/example.com/html/index.html

Add the following HTML code to this file and save it:

Welcome to your_domain!

Success! The your_domain server block is working!

sudo nano

Step #3: Configure the Server Block

Now, open and configure the NGINX server block configuration file with the following command:

# sudo nano /etc/nginx/sites-available/example.com

Add the following lines to configure the server block:

server {

listen 80;

server_name example.com www.example.com;

root /var/www/example.com/html;

index index.html;

location / {

try_files $uri $uri/ =404;

}

}

Configure the Server Block

Here, NGINX listens to incoming HTTP traffic on port 80. Now, if you want to force all traffic to use HTTPS, you can create a separate server block that redirects HTTP traffic to HTTPS:

server {

listen 80;

server_name example.com www.example.com;

return 301 https://$host$request_uri;

}

Step #4: Enable Configuration

NGINX uses a two-directory system for managing server blocks:

  • sites-available/: Holds all individual site configuration files, whether active or not.
  • sites-enabled/: Contains symlinks to the configurations in sites-availablethat you want NGINX to load and serve.

NGINX only reads the configuration files present insites-enabled. Therefore, create a symlink to enable your site:

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

If you do not want to use the default website configuration that comes with NGINX, you can disable it, so NGINX stops serving that default site.

Now test the configuration and reload to apply changes.

# sudo nginx -t

# sudo systemctl reload nginx

sudo systemctl reload nginx

You have now successfully set up the NGINX server block.

Getting Familiar with NGINX Configuration Files

For effective server management and troubleshooting, you need to have an understanding of the NGINX configuration files.

The following table summarizes the key NGINX configuration files:

File/ DirectoryPurpose
/etc/nginx/nginx.confMain configuration file, controls global settings
/etc/nginx/sites-available/Store server block configurations (virtual hosts)
/etc/nginx/sites-enabled/Active server blocks (symlinks from sites-available)
/var/www/htmlThe default document root for quick testing
/var/log/nginxLogs for access/error tracking
/run/nginx.pidTracks the main process ID

Tip: To tail logs for real-time monitoring, use the following commands:

sudo tail -f /var/log/nginx/access.log

sudo tail -f /var/log/nginx/error.log

Performance Tuning for High-Traffic Servers

Optimizing NGINX for high-traffic scenarios can be done through the following:

  • Enable caching and compression: By storing frequently accessed data in cache and configuring NGINX to access it, you can optimize the performance and time.
  • Use load balancing upstream blocks: During high incoming network traffic, distributing them across servers by setting up a load balancer, like NGINX, can prevent overburdening a single server.
  • Tweak worker connections and timeouts: By increasing the number of worker connections and configuring NGINX for the number of buffer sizes and timeouts, you can optimize performance.

worker_processes auto;

events {

worker_connections 1024;

}

http {

keepalive_timeout 65;

gzip on;

}

Securing Your NGINX Server with SSL

SSL/TLS encryption is essential for modern web applications. Follow the steps below to secure the NGINX server with SSL.

Step #1: Install Certbot via Snap

Start by installing Certbot via snap packages. Snap packages provide the most up-to-date version of Certbot with automatic updates.

# sudo snap install –classic certbot

sudo snap install

Step #2: Verify Certbot Installation

Now, verify the installation by checking the installed version with the following command:

# certbot –version

certbot --version

Step #3: Allow HTTP Port for Verification

Certbot often verifies domain ownership by connecting to the server on port 80.

If you only opened Nginx Full(typically includes rules that let both HTTP (port 80) and HTTPS (port 443) traffic), this step is redundant. However, if you open Nginx HTTPS or a custom port, ensure port 80 is open temporarily.

# sudo ufw allow 80

sudo ufw allow 80

Step #4: Generate SSL Certificate

Once the HTTP port is opened, run the following command to generate an SSL certificate:

# sudo certbot –nginx -d app.example.com

Now, Certbot automatically:

  • Validates domain ownership via HTTP
  • Generates SSL certificate and private key
  • Modifies your NGINX configuration to include SSL settings
  • Adds automatic HTTP to HTTPS redirect
  • Sets up automatic certificate renewal

Important: It is a good security practice to close HTTP connections after Certbot verification. This closes a critical and oft-ignored security loophole that attackers can exploit to connect to an open port. We suggest running the following command after you have set up the SSL certificate:

sudo ufw deny 80

Configuring NGINX as a Reverse Proxy

NGINX can act as a reverse proxy, where it forwards client requests to backend application servers (e.g., Node.js, Python Flask/Django, Java applications) when hosting multiple applications on the same server. This provides benefits like load balancing, SSL termination, and caching.

To configure NGINX as a reverse proxy:

  • Define upstream services:

Specify the backend servers (like your application servers) that NGINX will forward requests to

  • Modify the location/block to forward requests:

Set up a location block in the server configuration to tell NGINX where to pass incoming requests

  • Set headers and timeouts for optimal performance:

Configure appropriate headers (such as Host, X-Forwarded-For) so that the backend receives the right request information. Also, adjust timeout settings to handle slow backend responses without dropping connections.

upstream app_servers {

server 127.0.0.1:3000;

}

server {

listen 80;

server_name app.example.com;

location / {

proxy_pass http://app_servers;

proxy_set_header Host $host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_set_header X-Forwarded-Proto $scheme;

proxy_connect_timeout 60;

proxy_read_timeout 60;

}

}

Troubleshooting Common NGINX Errors

The following table summarizes the common NGINX issues and their solutions.

ErrorCauseSolution
403 ForbiddenIncorrect file permissions or missing index.htmlCheck ownership and permissions. Ensure the index file exists.
502 Bad GatewayThe backend application server is down or misconfiguredVerify the backend application is running. Check proxy configuration.
504 Gateway TimeoutThe backend service is unreachable or slowCheck backend health, firewall rules, and NGINX timeout settings.

Conclusion

Setting up NGINX on Ubuntu 22.04 involves a series of essential steps: installing the web server, configuring server blocks (virtual hosts), and securing your setup with SSL. Always remember to conduct regular testing with nginx -tbefore reloading configurations to prevent errors and maintain stability.

If you need more troubleshooting tips and advanced configurations, you can check out the official NGINX documentation and participate in community support forums such as the NGINX Forum.

FAQs

Is NGINX better than Apache on Ubuntu?

NGINX is generally considered better than Apache on Ubuntu for high-performance, low-memory web hosting, especially for handling static content and concurrent connections efficiently.

Can I host multiple domains with NGINX?

Yes, NGINX supports hosting multiple domains on the same server using server blocks (virtual hosts) for each domain.

What’s the difference between reload and restart?

reload applies configuration changes without interrupting active connections, while restart completely stops and starts the NGINX service, affecting active traffic.

How do I check if SSL is working properly?

You can verify SSL is working by visiting your site with **https://**and using tools like openssl s_client or online SSL checkers.

Does NGINX require root access to manage?

Yes, managing NGINX (installation, configuration changes, restarts) typically requires root or sudo privileges on the server.

Written by

Manasa M

Technical Content Editor

Manasa is a Technical Content Editor at RedSwitches, known for turning complex technical concepts into clear, engaging content. With a background in copy editing, sub-editing, and technical writing, she shapes the blog's guides for accuracy, readability, and search performance.

Related Articles

Power Your Next Project With Bare Metal

10 min delivery, zero setup fees, and 24/7/365 human engineers across 20+ global locations.