Setup Nginx Virtual Hosts on Ubuntu VPS: Multi-Domain Configuration

What Are Nginx Virtual Hosts and Why Use Them
Virtual hosts let you run multiple websites on a single server. Think of them as separate apartments in the same building—each domain gets its own space while sharing the same physical hardware.
When you setup Nginx virtual hosts on Ubuntu VPS, you can host dozens of websites without needing separate servers. This saves money and simplifies management for agencies, developers, and businesses running multiple sites.
Each virtual host operates independently. One site can run WordPress while another serves a static portfolio. If one site experiences traffic spikes, the others remain unaffected. Our Hostperl VPS customers regularly use this approach to manage client websites efficiently.
Prerequisites and Server Preparation
Before configuring virtual hosts, ensure your Ubuntu VPS meets these requirements:
- Ubuntu 20.04 or later with root access
- Nginx installed and running
- Domain names pointed to your server's IP address
- Basic familiarity with command line
Check if Nginx is installed:
sudo systemctl status nginx
If not installed, run:
sudo apt update
sudo apt install nginx
Verify your domains are properly pointed to your server by checking DNS propagation. Use dig yourdomain.com to confirm the A record points to your VPS IP address.
Create Directory Structure for Multiple Sites
Organize your websites with a clear directory structure. This makes maintenance easier as your hosting grows.
Create the main directory structure:
sudo mkdir -p /var/www/example1.com/html
sudo mkdir -p /var/www/example2.com/html
sudo mkdir -p /var/www/example1.com/logs
sudo mkdir -p /var/www/example2.com/logs
Set proper ownership:
sudo chown -R $USER:$USER /var/www/example1.com/html
sudo chown -R $USER:$USER /var/www/example2.com/html
Create simple index files for testing:
echo "<h1>Welcome to example1.com</h1>" > /var/www/example1.com/html/index.html
echo "<h1>Welcome to example2.com</h1>" > /var/www/example2.com/html/index.html
This structure keeps each site's files and logs separate, making troubleshooting and backup automation more straightforward.
Configure Nginx Virtual Hosts for Each Domain
Nginx uses server blocks instead of virtual hosts. Each server block defines how Nginx handles requests for a specific domain.
Create the first server block configuration:
sudo nano /etc/nginx/sites-available/example1.com
Add this configuration:
server {
listen 80;
listen [::]:80;
root /var/www/example1.com/html;
index index.html index.htm index.php;
server_name example1.com www.example1.com;
access_log /var/www/example1.com/logs/access.log;
error_log /var/www/example1.com/logs/error.log;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
Create the second server block:
sudo nano /etc/nginx/sites-available/example2.com
Use similar configuration but change the domain name and paths accordingly. This modular approach makes adding more sites simple without affecting existing configurations.
Enable Sites and Test Configuration
Enable your server blocks by creating symbolic links:
sudo ln -s /etc/nginx/sites-available/example1.com /etc/nginx/sites-enabled/
sudo ln -s /etc/nginx/sites-available/example2.com /etc/nginx/sites-enabled/
Test your Nginx configuration for syntax errors:
sudo nginx -t
You should see "syntax is ok" and "test is successful." If there are errors, double-check your server block configurations.
Reload Nginx to apply changes:
sudo systemctl reload nginx
Test each domain by visiting them in your browser. You should see the respective welcome messages you created earlier. If sites don't load, check your DNS settings and firewall rules.
Add SSL Certificates with Let's Encrypt
Secure your virtual hosts with free SSL certificates. Modern browsers flag non-HTTPS sites as unsafe, making SSL essential.
Install Certbot:
sudo apt install certbot python3-certbot-nginx
Obtain certificates for both domains:
sudo certbot --nginx -d example1.com -d www.example1.com
sudo certbot --nginx -d example2.com -d www.example2.com
Certbot automatically modifies your Nginx configuration to include SSL settings. It also sets up HTTP to HTTPS redirects.
Test automatic renewal:
sudo certbot renew --dry-run
This ensures your certificates will renew automatically before expiring. SSL management becomes hands-off once properly configured.
Security Hardening for Virtual Hosts
Implement security measures to protect all hosted domains:
Create a common security snippet:
sudo nano /etc/nginx/snippets/security-headers.conf
Add these headers:
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Referrer-Policy "strict-origin-when-cross-origin";
add_header Content-Security-Policy "default-src 'self'";
Include this snippet in each server block:
include snippets/security-headers.conf;
Consider implementing Fail2Ban protection to guard against brute force attacks across all your virtual hosts. This provides an additional security layer for hosting environments.
Performance Optimization Techniques
Optimize Nginx for hosting multiple sites efficiently:
Enable Gzip compression in your main configuration:
sudo nano /etc/nginx/nginx.conf
Uncomment and configure the gzip section:
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
Set appropriate worker processes:
worker_processes auto;
worker_connections 1024;
These optimizations improve response times across all virtual hosts. Monitor server resources to ensure your VPS can handle the load as you add more sites.
Monitoring and Log Management
Each virtual host generates separate access and error logs. This separation simplifies troubleshooting and analytics.
Monitor log files in real-time:
sudo tail -f /var/www/example1.com/logs/access.log
sudo tail -f /var/www/example1.com/logs/error.log
Set up log rotation to prevent disk space issues:
sudo nano /etc/logrotate.d/nginx-vhosts
Add this configuration:
/var/www/*/logs/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 644 www-data www-data
postrotate
systemctl reload nginx
endscript
}
This automatically compresses and rotates logs, keeping 30 days of history while managing disk space efficiently.
Troubleshooting Common Virtual Host Issues
Address frequent problems when hosting multiple domains:
Domain shows default Nginx page: Check if the server block is enabled and reload Nginx. Verify DNS points to your server IP.
SSL certificate errors: Ensure all domain variations are included in the certificate. Run sudo certbot certificates to check coverage.
File permissions issues: Verify ownership with ls -la /var/www/. Files should be owned by your user, directories should be 755.
PHP not processing: Check if PHP-FPM is running: sudo systemctl status php8.1-fpm. Ensure the socket path matches your configuration.
Keep configuration files backed up. When managing multiple sites, small syntax errors can affect all domains. Our migration planning guide covers best practices for maintaining hosting environments.
Managing multiple websites on a single VPS requires reliable hosting infrastructure. Hostperl VPS hosting provides the performance and support you need for virtual host environments. Our team helps with migrations, SSL setup, and ongoing server management to keep your sites running smoothly.
Frequently Asked Questions
How many virtual hosts can I run on one VPS?
The number depends on your VPS resources and site traffic. A 2GB RAM VPS can typically handle 20-50 low-traffic sites. Monitor CPU and memory usage as you scale up.
Can I use different PHP versions for different virtual hosts?
Yes, install multiple PHP-FPM versions and specify different sockets in each server block. This allows running legacy applications alongside modern sites.
What happens if one virtual host gets hacked?
Proper file permissions and separate directories limit damage. However, consider using containers or separate VPS instances for high-security applications.
How do I backup individual virtual hosts?
Create separate backup scripts for each domain's files and databases. This allows selective restoration without affecting other hosted sites.
Should I use wildcard SSL certificates for multiple subdomains?
Wildcard certificates work well for multiple subdomains of the same domain. For completely different domains, use separate certificates or multi-domain certificates.
