Skip to main content
Nginx is a popular open-source web server that can be used to serve static files, dynamic content, and proxy requests to other servers. It is known for its high performance, scalability, and security. In this tutorial, we will learn how to install and configure Nginx on any VPS.

Prerequisites

Before installing Nginx, make sure you have the following prerequisites:
  • A server with root access
  • A domain name or IP address
  • A web server that can be used to serve static files

Installing Nginx on Ubuntu

To install Nginx on Ubuntu, follow these steps:
1

Update the package index

sudo apt update
2

Install Nginx

sudo apt install nginx
3

Start and enable Nginx

sudo systemctl start nginx
sudo systemctl enable nginx
4

Verify installation

Open your web browser and navigate to http://your_server_ip. You should see the Nginx default welcome page.

Configuring Nginx on Ubuntu

1

Create a new server block configuration file

sudo vim /etc/nginx/sites-available/default
This command opens the default configuration file for editing.
2

Replace the file content with the following content

server {
  listen 80;  # Listen on port 80, the default HTTP port
  server_name localhost;  # The server name, here it is set to localhost

  root /var/www/html;  # The root directory where files are served from
  index index.html index.htm;  # The default files to serve

  location / {
    try_files $uri $uri/ =404;  # Try to serve the requested URI, if not found return a 404
  }
}
3

Create the document root directory if it doesn't exist

sudo mkdir -p /var/www/html
4

Change ownership of the document root directory to the current user

sudo chown -R $USER:$USER /var/www/html
5

Set the permissions for the document root directory

sudo chmod -R 755 /var/www/html
6

Create the directory for the web root

cd /var/www/html
This command navigates to the web root directory.
7

Create an empty index.html file

touch index.html
This command creates an empty index.html file.
8

Open the index.html file for editing

sudo vim index.html
This command opens the index.html file for editing.
9

Add the following content to the index.html file

<html>
  <head>
    <title>Welcome to Nginx</title>
  </head>
  <body>
    <h1>Hello, world!</h1>
  </body>
</html>
10

Test the Nginx configuration

sudo nginx -t
This command tests the Nginx configuration for syntax errors.
11

Reload Nginx to apply the changes

sudo systemctl reload nginx
This command reloads the Nginx service to apply the changes.
12

Verify the configuration

Open your web browser and navigate to URL_ADDRESS_server_ip. You should see the Nginx default welcome page.

Summary

In this tutorial, we learned how to install and configure Nginx to serve static files.

Next: Nginx Rate Limiting

Continue your journey by learning how to implement rate limiting with Nginx.