Nginx (pronounced as “engine x”) is a super-efficient, open-source HTTP and reverse proxy server. It handles the load for some of the biggest websites on the internet, you see. This guide will teach you how to configure Nginx server blocks to host multiple websites on a single Ubuntu 22.04 server.
Prerequisites
Make sure you have met the following requirements before we proceed:
- Your domain name is pointing to your server’s public IP address.
- Nginx is properly installed on your Ubuntu system.
- You have root or sudo privileges to run commands.
Understanding Server Blocks
A server block is an Nginx directive that defines settings for a specific domain. It allows you to run multiple websites on one server, with separate configurations for each, such as:
- The site document root (the directory where website files are stored)
- Security policies
- SSL certificates
Creating the Directory Structure
The document root is where the website files are stored and served from. We’ll use this directory structure:
/var/www/ ├── domain1.com │ └── public_html ├── domain2.com │ └── public_html
Each domain’s document root will be /var/www/<domain>/public_html
.
Step 1: Create the Domain Directory
sudo mkdir -p /var/www/domain1.com/public_html
Step 2: Create the index.html File
Place an index.html file in the domain’s root directory:
/var/www/domain1.com/public_html/index.html <!DOCTYPE html> <html> <head> <title>domain1.com</title> </head> <body> <h1>Success! domain1.com home page!</h1> </body> </html>
Step 3: Change the Ownership
sudo chown -R www-data: /var/www/domain1.com
This avoids permission issues by setting the Nginx user (www-data) as the owner.
Also Read: How to Create Directories with the mkdir Command in Linux
Creating a Server Block
Step 1: Create the Config File
/etc/nginx/sites-available/domain1.com server { listen 80; server_name domain1.com www.domain1.com; root /var/www/domain1.com/public_html; index index.html; access_log /var/log/nginx/domain1.com.access.log; error_log /var/log/nginx/domain1.com.error.log; }
server_name
: The domain(s) that will match this server block configurationroot
: The directory from where Nginx will serve the domain filesaccess_log
,error_log
: The location for log files
Step 2: Enable the Config
sudo ln -s /etc/nginx/sites-available/domain1.com /etc/nginx/sites-enabled/
This creates a symbolic link from the config file to the sites-enabled directory, which Nginx reads during startup.
Step 3: Test the Nginx Config
sudo nginx -t
Step 4: Restart Nginx
sudo systemctl restart nginx
Verification
Open http://domain1.com in your browser – you should see the “Success!” message displayed, all being well.
Conclusion
Repeat these steps to add more domains by creating new directories, index files, and server block configs. With Nginx server blocks, you can efficiently host and configure multiple websites on a single Ubuntu server, isn’t it?