Complete Guide to Installing and Configuring Nginx on Ubuntu [Beginner-Friendly]

1. Introduction

Many people want to use Nginx on Ubuntu, but if you are new to it, you might not know where to start. This article provides a step-by-step guide for beginners, covering everything from installation and configuration to management on an Ubuntu environment.

What is Nginx?

Nginx (pronounced “engine-x”) is a high-performance HTTP server and reverse proxy server. It is widely used worldwide for its lightweight design and flexibility, especially its ability to handle high traffic loads.

Benefits of Using Nginx on Ubuntu

Ubuntu is a popular Linux distribution that works well with Nginx. With its package management system (APT), installing and updating Nginx is easy, and it offers excellent stability and security.

By reading this article, you will learn:

  • How to install Nginx on Ubuntu
  • Basic configuration and management procedures
  • Performance tuning and troubleshooting

Now, let’s get started.

2. How to Install Nginx on Ubuntu

To run Nginx on Ubuntu, you first need to install it correctly. This section provides a clear, step-by-step guide to the installation process.

Checking Required Packages

Before starting the installation, make sure your system is up to date by running the following commands:

sudo apt update
sudo apt upgrade

Installing Nginx

To install Nginx, enter the following command:

sudo apt install nginx

This command automatically downloads and installs Nginx from Ubuntu’s APT repository.

Verifying the Installation

To check if the installation was successful, use the following command to check the Nginx status:

sudo systemctl status nginx

If the output shows “active (running),” the installation was successful.

Configuring the Firewall

Ubuntu includes UFW (Uncomplicated Firewall), which you can use to allow Nginx traffic.

sudo ufw allow 'Nginx Full'
sudo ufw enable

Now, Nginx is set up to operate on ports 80 (HTTP) and 443 (HTTPS).

侍エンジニア塾

3. Basic Nginx Configuration on Ubuntu

Simply installing Nginx is not enough. Next, you need to configure it properly for effective use.

Configuration Files and Basic Structure

The main Nginx configuration files are located in:

  • Main configuration file: /etc/nginx/nginx.conf
  • Site-specific configuration files: Inside the /etc/nginx/sites-available/ directory

Typically, you create a virtual host configuration file in sites-available and create a symbolic link to sites-enabled for activation.

Setting Up a Virtual Host

Virtual hosts allow you to manage multiple domains or projects on a single server. The following example sets up example.com:

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

Enter the following content:

server {
    listen 80;
    server_name example.com www.example.com;

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

    location / {
        try_files $uri $uri/ =404;
    }
}

Save the file and activate the configuration with the following commands:

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

Configuring SSL/TLS

To enable secure communication, set up an SSL/TLS certificate. You can use Let’s Encrypt to obtain a free certificate.

First, install certbot:

sudo apt install certbot python3-certbot-nginx

Next, run the following command to obtain and automatically configure the SSL certificate:

sudo certbot --nginx -d example.com -d www.example.com

To prevent expiration, also set up automatic certificate renewal.

4. Managing and Controlling Nginx

After installing and configuring Nginx, you need to learn how to start, stop, reload configurations, and troubleshoot issues. This section covers essential management commands and troubleshooting techniques.

Basic Nginx Commands

On Ubuntu, you can manage Nginx using the systemctl command. Here are the key operations:

  1. Start Nginx
sudo systemctl start nginx
  1. Stop Nginx
sudo systemctl stop nginx
  1. Restart Nginx
    Required when making major configuration changes.
sudo systemctl restart nginx
  1. Reload Nginx
    Apply configuration changes without restarting.
sudo systemctl reload nginx
  1. Check Nginx Status
    Verify if Nginx is running properly.
sudo systemctl status nginx

Enabling Automatic Startup

To ensure Nginx starts automatically after a system reboot:

  1. Enable auto-start
sudo systemctl enable nginx
  1. Disable auto-start (if needed)
sudo systemctl disable nginx

Checking Logs for Troubleshooting

If Nginx is not working as expected, check the logs to find the cause.

  1. View Error Logs
sudo tail -f /var/log/nginx/error.log
  1. View Access Logs
sudo tail -f /var/log/nginx/access.log

5. Configuring the Nginx Firewall and Enhancing Security

Security is crucial when operating Nginx. This section explains how to configure ports using Ubuntu’s firewall (UFW) and strengthen Nginx security.

Opening Ports Using UFW

UFW (Uncomplicated Firewall) is a firewall tool included in Ubuntu by default. To ensure Nginx functions properly, you need to open ports 80 (HTTP) and 443 (HTTPS).

  1. Check the current UFW status
sudo ufw status
  1. Allow Nginx traffic
    Run the following command to open the necessary ports:
sudo ufw allow 'Nginx Full'
  1. Enable UFW
    If the firewall is disabled, enable it:
sudo ufw enable

Additional Security Enhancements

  1. Disable Unnecessary HTTP Methods
    To enhance security, disable unnecessary HTTP methods by adding the following to the Nginx configuration file:
if ($request_method !~ ^(GET|POST|HEAD)$) {
    return 444;
}
  1. Disable Directory Listing
    Prevent directory contents from being publicly accessible by adding:
autoindex off;
  1. Strengthen SSL/TLS
    Use strong encryption settings in your SSL configuration:
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers HIGH:!aNULL:!MD5;

6. Nginx Performance Tuning and Troubleshooting

Nginx is widely known for its high performance, but proper tuning can further improve its efficiency. This section covers optimization techniques and common troubleshooting solutions.

Performance Tuning

1. Configuring Worker Processes

Nginx follows a multi-process architecture. Setting an appropriate number of worker processes optimizes performance.

Edit the configuration file /etc/nginx/nginx.conf and set:

worker_processes auto;

The “auto” setting automatically adjusts the number of worker processes based on the CPU cores.

2. Increase Worker Connections

By default, each worker process has a limited number of connections. Increasing this value improves handling of high traffic loads.

Add or modify the following line in the configuration file:

worker_connections 1024;

3. Enable HTTP/2

Enabling HTTP/2 improves communication efficiency and speeds up website loading.

Modify the /etc/nginx/sites-available/example.com file and change the listen directive as follows:

listen 443 ssl http2;

Then reload Nginx:

sudo systemctl reload nginx

4. Enable Content Compression

Compressing files before sending them reduces bandwidth usage and improves loading times.

Add or enable the following settings:

gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

5. Configure Caching

Setting up caching reduces repeated requests for static resources.

Add the following configuration:

location ~* .(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|svg)$ {
    expires 30d;
    access_log off;
}

Common Troubleshooting

1. Slow Request Handling Under High Load

  • Cause: Insufficient worker processes or connection limits.
  • Solution: Adjust worker processes and connections, or consider using a load balancer.

2. “403 Forbidden” Error

  • Cause: Incorrect root directive in the configuration file or incorrect file permissions.
  • Solution: Check the root directive and update file permissions:
sudo chmod -R 755 /var/www/example.com/html
sudo chown -R www-data:www-data /var/www/example.com/html

3. Server Timeout Issues

  • Cause: Long request processing time.
  • Solution: Adjust timeout settings:
proxy_read_timeout 300;
proxy_connect_timeout 300;
proxy_send_timeout 300;

4. Nginx Restart Errors

  • Cause: Configuration file errors.
  • Solution: Test the configuration before restarting:
sudo nginx -t

7. Summary and Next Steps

In this guide, we covered how to install, configure, and manage Nginx on Ubuntu. Let’s review what we have learned and explore the next steps.

Summary of Key Points

1. Installing Nginx on Ubuntu

  • Prepared required packages and installed Nginx using APT.
  • Configured the firewall to allow Nginx traffic.

2. Basic Configuration

  • Understood Nginx’s configuration file structure and set up virtual hosts and SSL/TLS.

3. Managing Nginx

  • Learned essential commands for starting, stopping, and reloading Nginx.
  • Checked logs for troubleshooting.

4. Security Enhancements

  • Configured UFW and applied additional security settings.

5. Performance Tuning and Troubleshooting

  • Optimized worker processes, enabled HTTP/2, and set up caching.
  • Addressed common Nginx issues.

Next Steps

Now that you have the fundamentals of Nginx on Ubuntu, consider these next steps:

  • Learn advanced configurations like load balancing and reverse proxy.
  • Enhance security with WAF and additional Nginx security modules.
  • Automate deployments using Ansible or Docker.
  • Monitor performance with tools like Prometheus and Grafana.

By applying these concepts, you can effectively run and manage a high-performance web server with Nginx on Ubuntu.