Configuring multiple websites on a single Nginx server requires proper configuration to ensure each domain is routed to the correct web root. This post explains how to set up two example sites using Nginx and also how to update DNS settings when using Cloudflare as a CDN.
user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; } http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # Include configurations for available sites include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; }
This file includes references to sites-enabled
, where individual site configurations will be included.
In /etc/nginx/sites-available
, create a configuration file for each website.
server { listen 80; server_name site1.dev www.site1.dev; root /var/www/site1; index index.html; location / { try_files $uri $uri/ =404; } }
server { listen 80; server_name site2.dev www.site2.dev; root /var/www/site2; index index.html; location / { try_files $uri $uri/ =404; } }
Create symbolic links in sites-enabled
to enable each site:
sudo ln -s /etc/nginx/sites-available/site1.dev /etc/nginx/sites-enabled/ sudo ln -s /etc/nginx/sites-available/site2.dev /etc/nginx/sites-enabled/
Test your Nginx configuration and restart the service:
sudo nginx -t sudo systemctl restart nginx
If you are using a CDN like Cloudflare, you must update your DNS records to point to the server's IP. Here is an example of a DNS A record configuration in Cloudflare:
To ensure proper routing through Cloudflare:
A
.www
).These changes ensure that traffic to your domain is correctly routed through Cloudflare’s CDN, optimizing performance and providing security features like SSL.
Nginx allows you to host multiple websites by separating their configurations in sites-available
and linking them to sites-enabled
. Additionally, updating DNS settings in Cloudflare ensures your site is properly routed through the CDN for better performance and security.