How to install and set up Nginx as a web server on Ubuntu Server 20.04
Installing Nginx
Follow these steps to install Nginx:
Step 1 : Update the apt package repository and install Nginx.
sudo apt update
sudo apt install nginx
Step 2 : Check if Nginx is properly installed and running
sudo service nginx status
Step 3 : Check the installed version of Nginx
nginx -v
Step 4 : Open a browser on a local machine and point it to the server IP address.
Configuring Nginx Server Block (Virtual host)
Step 5 : Change the directory to /var/www and create a directory structure for the required domains and sub-domain. Also create a blank index.html for each domain
cd /var/www
sudo mkdir -p example.com/html
sudo touch example.com/html/index.html
Step 6 : Change the directory ownership and file permissions on the newly created directories
sudo chown -R $USER:www-data example.com
sudo chmod 755 -R example.com
Step 7 : Edit the index.html
nano example.com/html/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome</h1>
</body>
</html>
Step 8 : Next, we need to create virtual host configuration for each domain. Change the directory to /etc/nginx/sites-available and copy the default virtual host file default
cd /etc/nginx/sites-available
sudo cp default example.com
Step 9 : Edit the new virtual host file
sudo nano example.com
server {
listen 80;
listen [::]:80;
root /var/www/example.com/html;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name example.com www.example.com;
location / {
try_files $uri $uri/ =404;
}
}
Step 10 : Let’s enable the file by creating a link from it to the sites-enabled directory
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
Step 11 : To test the Nginx configuration, run the following command
sudo nginx -t
Step 12 : Restart Nginx to enable your changes
sudo service nginx restart
Step 13 : Finally, try to access domains by their names. You should see text entered in the respective index.html files for each domain: