Nginx is a high-performance web server that can also be used as a reverse proxy, load balancer, and HTTP cache. It is known for its scalability and speed. In this tutorial, you’ll learn how to install Nginx on Ubuntu 22.04, manage the Nginx service, configure the firewall, and set up server blocks (virtual hosts) to host multiple websites on a single server.
Table of contents [Show]
First, update the system package index:
sudo apt update && sudo apt upgrade -y
Use the default package manager to install Nginx:
sudo apt install nginx -y
After installation, verify it:
nginx -v
Allow Nginx traffic through the UFW firewall:
sudo ufw allow 'Nginx Full'
Check UFW status:
sudo ufw status
Enable and start the Nginx service:
sudo systemctl enable nginx
sudo systemctl start nginx
Check status:
sudo systemctl status nginx
Open your browser and go to your server's IP address:
http://your_server_ip
You should see the default Nginx welcome page.
Server blocks allow you to host multiple domains on a single server. We’ll set up an example block for example.com.
sudo mkdir -p /var/www/example.com/html
sudo chown -R $USER:$USER /var/www/example.com/html
sudo chmod -R 755 /var/www/example.com
nano /var/www/example.com/html/index.html
Add the following content:
<html>
<head>
<title>Welcome to Example.com</title>
</head>
<body>
<h1>Success! Your Nginx server block is working.</h1>
</body>
</html>
sudo nano /etc/nginx/sites-available/example.com
Paste the following configuration:
server {
listen 80;
listen [::]:80;
root /var/www/example.com/html;
index index.html index.htm;
server_name example.com www.example.com;
location / {
try_files $uri $uri/ =404;
}
}
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
Point your domain’s DNS A record to your server's IP address so that example.com loads correctly.
To host multiple domains, repeat steps above with new directories, index.html, and config files (e.g., test.com
).
To secure your Nginx sites with HTTPS using Let's Encrypt:
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d example.com -d www.example.com
Set up automatic renewal:
sudo certbot renew --dry-run
You have successfully installed Nginx on Ubuntu 22.04, configured the firewall, and set up server blocks to host multiple websites. You can now extend this by adding SSL, reverse proxy setups, PHP integration, and performance optimization.
Your email address will not be published. Required fields are marked *