How to install and configure Nginx on Ubuntu

How to install and configure Nginx on Ubuntu

Nginx, one of the most widely used HTTP web servers in the world today, offers a variety of features such as reverse proxy, load balancing, and content caching. Despite its ability to host highly trafficked websites, it can be installed and configured with very simple steps.
Cemil Tokatli
January 9, 2025
Share:

In this article, we will explore how to install Nginx on an Ubuntu server and configure it to serve a simple HTML document.

You can install Nginx on your Ubuntu server by following the steps below.

1. Update packages:

sudo apt update -y

2. Install Nginx:

sudo apt install -y nginx

3. Create a folder to store our document:

We need a folder to install our application files or web documents.

mkdir /home/mydomain.com

4. Create a sample HTML file:

We also need to create a sample document to ensure that our server configuration is working properly.

vi /home/mydomain.com/index.html

Copy and paste the text below into the document.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome to Nginx!</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 0; padding: 0; background: #f4f4f4; }
        header { background: #009639; color: #fff; padding: 20px; text-align: center; }
        main { max-width: 800px; margin: 50px auto; padding: 20px; background: #fff; border-radius: 8px; }
    </style>
</head>
<body>
    <header>
        <h1>Welcome to Your Nginx Server</h1>
    </header>
    <main>
        <h2>Setup Complete!</h2>
        <p>Your Nginx server is now running successfully. Customize this page to fit your needs!</p>
    </main>
</body>
</html>

5. Set up a server block:

We need to set up a server block (similar to virtual hosts in Apache) to serve a web page.

Go to /etc/nginx/sites-available directory and edit the default file.

server {
	listen 80 default_server; #If it is a secondary server, make sure "default_server" is removed
 	listen [::]:80 default_server; #If it is a secondary server, make sure this line is removed

	server_name mydomain.com;
	
	location / {
		root   /home/mydomain.com;
		index  index.html index.htm;
	}
}

6. Restart Nginx:

systemctl restart nginx

Conclusion:

You can test your Nginx configuration by navigating to http://your-ip or http://your-domain on your browser, where you should see your sample HTML document:

When you update your Nginx configuration, you can check the error logs with the following command:

nginx -t