How to Configure Multiple Sites in Nginx: Simple Guide
To configure multiple sites in
nginx, create separate server blocks for each site inside the sites-available directory, then enable them by linking to sites-enabled. Each server block defines the domain, root directory, and other settings for that site.Syntax
The basic syntax to configure multiple sites in nginx uses server blocks. Each block defines settings for one site, including the domain name and root folder.
server_name: The domain or subdomain for the site.root: The folder where the website files are stored.listen: The port number (usually 80 for HTTP).location: Defines how requests are handled.
nginx
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
location / {
try_files $uri $uri/ =404;
}
}Example
This example shows how to configure two sites, example.com and test.com, on one Nginx server using separate server blocks.
nginx
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
location / {
try_files $uri $uri/ =404;
}
}
server {
listen 80;
server_name test.com www.test.com;
root /var/www/test.com/html;
location / {
try_files $uri $uri/ =404;
}
}Output
When Nginx is reloaded, requests to example.com serve files from /var/www/example.com/html, and requests to test.com serve files from /var/www/test.com/html.
Common Pitfalls
Common mistakes when configuring multiple sites in Nginx include:
- Not creating symbolic links from
sites-availabletosites-enabled, so Nginx does not load the site configuration. - Forgetting to reload or restart Nginx after changes.
- Using the same
server_namein multiple blocks, causing conflicts. - Incorrect file permissions on the website root folder, preventing Nginx from reading files.
bash
## Wrong: Missing symbolic link # Configuration file in /etc/nginx/sites-available/example.com exists but not linked ## Right: Create symbolic link sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ ## Reload Nginx sudo systemctl reload nginx
Output
No output if successful; Nginx reloads with new site configurations.
Quick Reference
| Directive | Purpose | Example |
|---|---|---|
| listen | Port Nginx listens on | listen 80; |
| server_name | Domain names for the site | server_name example.com www.example.com; |
| root | Folder with site files | root /var/www/example.com/html; |
| location | Request handling rules | location / { try_files $uri $uri/ =404; } |
| include | Include other config files | include /etc/nginx/snippets/*.conf; |
Key Takeaways
Create separate server blocks for each site with unique server_name and root.
Enable site configs by linking from sites-available to sites-enabled.
Always reload Nginx after configuration changes to apply them.
Avoid duplicate server_name entries to prevent conflicts.
Check file permissions so Nginx can access site files.