How to Set Up an Nginx Web Server on Ubuntu

Introduction

Nginx (pronounced as Engine-X) is an open-source web server used to deliver website content over the internet. It is widely used because of its high performance, low resource consumption, and ability to handle multiple client connections efficiently.

A web server receives HTTP or HTTPS requests from web browsers and responds by delivering the requested website content. Nginx can serve static files such as HTML, CSS, JavaScript, and images. It can also work as a reverse proxy and load balancer for web applications.

Ubuntu is a popular Linux operating system for hosting websites and managing servers. Installing Nginx on Ubuntu provides a simple and reliable environment for deploying websites.

One important feature of Nginx is virtual hosting, which allows multiple websites to run on a single server. Each website can have its own domain name, configuration, and website directory while sharing the same server resources.

1. Understanding Nginx Web Server

Nginx is an event-driven web server that uses an asynchronous, non-blocking architecture to handle multiple connections efficiently.

When a visitor enters a website address in a browser, the browser sends a request to the server. Nginx receives the request, identifies the requested website, and returns the appropriate content.

For example, when a visitor opens:

http://example.com

The following process takes place:

  1. The browser requests the website.
  2. DNS resolves the domain name to an IP address.
  3. The browser connects to the server using the appropriate port.
  4. Nginx receives the HTTP request.
  5. Nginx identifies the requested website using its configuration.
  6. Nginx serves the requested files or forwards the request to a backend application.
  7. The browser displays the website.

Key Features of Nginx

  • High Performance: Handles multiple simultaneous connections efficiently.
  • Static Content Delivery: Serves HTML, CSS, JavaScript, images, and other static files.
  • Reverse Proxy: Forwards client requests to backend applications.
  • Load Balancing: Distributes incoming requests across multiple backend servers.
  • Virtual Hosting: Allows multiple websites to run on one server.
  • HTTPS Support: Supports secure communication using SSL/TLS certificates.

2. Installing Nginx on Ubuntu

Before installing Nginx, you need an Ubuntu server, a user account with sudo privileges, and an active internet connection.

Step 1: Update Ubuntu Packages

First, update the package information to ensure that Ubuntu has the latest available package details.

sudo apt update

To upgrade installed packages, run:

sudo apt upgrade -y

Step 2: Install Nginx

Install Nginx using the APT package manager:

sudo apt install nginx -y

This command downloads and installs Nginx along with the required dependencies.

Step 3: Start and Enable Nginx

After installation, start the Nginx service:

sudo systemctl start nginx

Enable it to start automatically when Ubuntu boots:

sudo systemctl enable nginx

Step 4: Verify Nginx Status

Check whether Nginx is running correctly:

sudo systemctl status nginx

If the installation is successful, the output should show:

Active: active (running)

You can also verify that Nginx responds locally:

curl -I http://localhost

A successful response commonly includes an HTTP status such as 200 OK.

Step 5: Configure the Firewall

Ubuntu uses UFW (Uncomplicated Firewall) to manage network access.

Allow HTTP traffic through port 80:

sudo ufw allow 80/tcp

Allow HTTPS traffic through port 443:

sudo ufw allow 443/tcp

If you are managing the server over SSH, make sure SSH is allowed before enabling UFW:

sudo ufw allow OpenSSH

Check the firewall configuration:

sudo ufw status

If UFW is inactive and you intend to enable it, first verify that your SSH access is permitted, then run:

sudo ufw enable

Cloud-hosted servers may also require ports 80 and 443 to be allowed in their provider-level firewall.

Step 6: Access the Nginx Web Server

Find your server’s IP addresses:

hostname -I

For internet access, use the server’s public IP address in your browser:

http://YOUR_SERVER_IP

Replace YOUR_SERVER_IP with your actual public IP address.

If Nginx is running correctly and network access is configured, the default Nginx welcome page will appear.

Nginx is now installed and running on Ubuntu.

3. Understanding Nginx Configuration

Nginx stores its main configuration files in:

/etc/nginx/

The important files and directories are:

Path Description
/etc/nginx/nginx.conf Main Nginx configuration file
/etc/nginx/sites-available/ Stores website configuration files
/etc/nginx/sites-enabled/ Contains enabled website configurations
/var/www/html/ Default website directory
/var/log/nginx/access.log Stores incoming request logs
/var/log/nginx/error.log Stores error logs

Ubuntu commonly uses sites-available and sites-enabled to manage multiple websites.

  • sites-available: Stores configuration files for all websites, including websites that are not currently active.
  • sites-enabled: Contains symbolic links to the configurations that Nginx should load.

This separation makes it easier to enable or disable websites without deleting their original configuration files.

4. Understanding IP Addresses and Virtual Hosting

What Is an IP Address?

An IP (Internet Protocol) address is a numerical address assigned to a device or network interface to identify it on a network and enable communication.

A web server uses an IP address to receive requests from clients.

There are two main types of IP addresses:

Public IP Address

A public IP address is used to identify a server on the internet. It allows users to connect to the server from external networks, provided that the required ports and firewall rules are configured.

Example:

203.0.113.10

This is an example address reserved for documentation purposes.

Private IP Address

A private IP address is used within a local network and is generally not directly accessible from the public internet.

Common private IPv4 ranges are:

  • 10.0.0.0/8
  • 172.16.0.0/12
  • 192.168.0.0/16

A server can have multiple IP addresses, and Nginx can be configured to listen on specific IP addresses and ports.

What Is Virtual Hosting?

Virtual hosting is a technique that allows multiple websites to run on a single physical or virtual server.

Without virtual hosting, organizations might need separate servers for different websites. Virtual hosting makes it possible to manage multiple domains using the same server resources.

For example, consider an Ubuntu server with the following public IP address:

203.0.113.10

Suppose you want to host two websites:

www.website-one.com
www.website-two.com

Both domain names can point to the same IP address. Nginx identifies the requested website using its configuration and serves the corresponding website files.

Each website can have its own:

  • Domain name
  • Document root directory
  • Nginx server block
  • Website files
  • Access and error logs
  • SSL/TLS certificate

There are two commonly used virtual hosting approaches.

4.1 IP-Based Virtual Hosting

IP-based virtual hosting allows multiple websites to run on the same server using different IP addresses.

In this approach, each website is configured to listen on a separate IP address.

For example:

Website IP Address
website-one.com 203.0.113.10
website-two.com 203.0.113.11
website-three.com 203.0.113.12

Nginx listens on the assigned IP addresses and selects the appropriate server configuration based on the destination address and port.

Example Nginx Configuration

For the first website:

server {
    listen 203.0.113.10:80;
    server_name website-one.com;

    root /var/www/website-one;
    index index.html;

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

For the second website:

server {
    listen 203.0.113.11:80;
    server_name website-two.com;

    root /var/www/website-two;
    index index.html;

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

In this configuration, each website uses a different IP address, even though both are hosted on the same server.

Advantages:

  • Provides a dedicated IP address for each website.
  • Useful when separate network addresses are required.
  • Allows explicit separation at the listening-address level.

Limitations:

  • Requires multiple IP addresses.
  • Additional IP addresses may increase hosting costs.
  • Requires additional network configuration.

4.2 Name-Based Virtual Hosting

Name-based virtual hosting allows multiple websites to share the same IP address.

Instead of identifying websites using different IP addresses, Nginx uses the domain name provided in the incoming request.

For example:

Website IP Address
website-one.com 203.0.113.10
website-two.com 203.0.113.10
website-three.com 203.0.113.10

All websites point to the same server IP address.

Nginx identifies the requested domain using the HTTP Host header and matches it with the server_name directive in the corresponding server block.

For HTTPS connections, Server Name Indication (SNI) allows the server to identify the requested hostname during the TLS handshake.

Example Nginx Configuration

For the first website:

server {
    listen 80;
    server_name website-one.com www.website-one.com;

    root /var/www/website-one;
    index index.html;

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

For the second website:

server {
    listen 80;
    server_name website-two.com www.website-two.com;

    root /var/www/website-two;
    index index.html;

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

Both websites listen on port 80 and use the same server IP address. However, Nginx serves different website content based on the requested domain name.

Advantages:

  • Multiple websites can share one public IP address.
  • Reduces the need for additional IP addresses.
  • Easier to configure and maintain.
  • Cost-effective for hosting multiple websites.

For most modern website hosting environments, name-based virtual hosting is the preferred approach.

Difference Between IP-Based and Name-Based Virtual Hosting

Feature IP-Based Name-Based
Identification Destination IP address Domain name
IP requirement Different IPs generally required One shared IP can be used
Configuration Specific IP in listen Domain in server_name
Cost Can be higher Generally lower
Common usage Special network requirements Most modern websites

5. Hosting Multiple Websites on a Single Ubuntu Server Using Nginx

Now let’s configure an Ubuntu server to host two different websites using one public IP address.

We will use name-based virtual hosting, where Nginx identifies each website using its domain name.

For this example, we will use:

website-one.com
website-two.com

Both websites will point to the same server IP address.

Step 1: Create Separate Website Directories

Create an individual directory for each website:

sudo mkdir -p /var/www/website-one
sudo mkdir -p /var/www/website-two

These directories will store the website files.

The directory structure will look like this:

/var/www/
    |
    |-- website-one/
    |      |-- index.html
    |
    |-- website-two/
           |-- index.html

Step 2: Create Website Files

Create the first website’s HTML file:

sudo nano /var/www/website-one/index.html

Add the following content:

<!DOCTYPE html>
<html>
<head>
    <title>Website One</title>
</head>
<body>
    <h1>Welcome to Website One</h1>
    <p>This website is hosted using Nginx on Ubuntu.</p>
</body>
</html>

Save and close the file.

Now create the second website’s HTML file:

sudo nano /var/www/website-two/index.html

Add:

<!DOCTYPE html>
<html>
<head>
    <title>Website Two</title>
</head>
<body>
    <h1>Welcome to Website Two</h1>
    <p>This is another website hosted on the same Nginx server.</p>
</body>
</html>

Save and close the file.

Step 3: Configure Website Permissions

Nginx needs permission to read the website files and access their parent directories.

For this example, set ownership and permissions as follows:

sudo chown -R www-data:www-data /var/www/website-one
sudo chown -R www-data:www-data /var/www/website-two

Set directory permissions:

sudo find /var/www/website-one -type d -exec chmod 755 {} \;
sudo find /var/www/website-two -type d -exec chmod 755 {} \;

Set file permissions:

sudo find /var/www/website-one -type f -exec chmod 644 {} \;
sudo find /var/www/website-two -type f -exec chmod 644 {} \;

The www-data user is commonly used by Nginx on Ubuntu.

Step 4: Create the First Nginx Server Block

Create a configuration file for the first website:

sudo nano /etc/nginx/sites-available/website-one

Add the following configuration:

server {
    listen 80;
    listen [::]:80;

    server_name website-one.com www.website-one.com;

    root /var/www/website-one;
    index index.html;

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

Explanation of the main directives:

  • listen 80: Accepts HTTP requests on port 80.
  • listen [::]:80: Enables listening on IPv6 port 80.
  • server_name: Specifies the domain names handled by this website.
  • root: Defines the website’s document root directory.
  • index: Specifies the default page to load.
  • location /: Defines how incoming requests are processed.
  • try_files: Checks whether the requested file or directory exists and returns a 404 error if it does not.

Save the configuration file.

Step 5: Create the Second Nginx Server Block

Create another configuration file:

sudo nano /etc/nginx/sites-available/website-two

Add:

server {
    listen 80;
    listen [::]:80;

    server_name website-two.com www.website-two.com;

    root /var/www/website-two;
    index index.html;

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

The configuration is similar to the first website, but the domain name and document root are different.

This allows Nginx to serve two independent websites using the same IP address and port.

Step 6: Enable Both Websites

The configuration files are stored in sites-available, but they must be enabled before Nginx can use them.

Create symbolic links for the first website:

sudo ln -s /etc/nginx/sites-available/website-one /etc/nginx/sites-enabled/

Enable the second website:

sudo ln -s /etc/nginx/sites-available/website-two /etc/nginx/sites-enabled/

Both website configurations are now enabled.

If you no longer need the default Nginx website, you can disable it by removing its symbolic link:

sudo rm /etc/nginx/sites-enabled/default

This does not delete the original default configuration file.

Step 7: Test the Nginx Configuration

Before applying the new configuration, check for syntax errors:

sudo nginx -t

If everything is correct, you should see output similar to:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

If there are errors, correct them before continuing.

Step 8: Reload Nginx

Apply the updated configuration:

sudo systemctl reload nginx

Nginx will now use the new server blocks.

Step 9: Configure DNS Records

To make both websites accessible through their domain names, configure DNS records with your domain registrar or DNS provider.

For each domain, create an A record pointing to the server’s public IP address.

Example:

Type Host Value
A @ YOUR_SERVER_IP
A www YOUR_SERVER_IP

Configure these records for both domains.

The DNS configuration should point to the same server:

website-one.com      → YOUR_SERVER_IP
www.website-one.com  → YOUR_SERVER_IP

website-two.com      → YOUR_SERVER_IP
www.website-two.com  → YOUR_SERVER_IP

An A record maps a domain name to an IPv4 address.

DNS changes may take some time to propagate, depending on the DNS provider and record TTL.

Step 10: Test Both Websites

Once DNS records are configured, open both domains in a browser:

http://website-one.com
http://website-two.com

You should see different website content for each domain, even though both websites are hosted on the same Ubuntu server.

You can also test the configuration locally before DNS propagation:

curl -H "Host: website-one.com" http://127.0.0.1
curl -H "Host: website-two.com" http://127.0.0.1

These commands send HTTP requests with different Host headers to the local Nginx server.

Each command should return the HTML content of the corresponding website.

Both websites are now configured and running on a single Nginx web server using name-based virtual hosting.

6. Managing the Nginx Service

The following commands are useful for managing Nginx on Ubuntu.

Operation Command
Check status sudo systemctl status nginx
Start Nginx sudo systemctl start nginx
Stop Nginx sudo systemctl stop nginx
Restart Nginx sudo systemctl restart nginx
Reload configuration sudo systemctl reload nginx
Enable at startup sudo systemctl enable nginx
Check version nginx -v
Test configuration sudo nginx -t

It is recommended to test the configuration using sudo nginx -t before reloading Nginx after making configuration changes.