How to host multiple domains on one server in nginx.conf
Configure multiple server blocks in nginx.conf to host different domains on the same server IP address with separate document roots.
Host multiple domains on a single server by creating separate server blocks in nginx.conf, each with its own
server_nameand document root.
Prerequisites
- Root or sudo access to the server running Nginx.
- DNS A records for each domain pointing to the server's public IP address.
- A separate document root directory for each domain (e.g.,
/var/www/domain1.com,/var/www/domain2.com).
Step-by-Step: Host Multiple Domains in nginx.conf
- Create the document root directories for each domain. Each domain needs its own directory to serve its files independently.
sudo mkdir -p /var/www/domain1.com
sudo mkdir -p /var/www/domain2.com- Open the nginx.conf configuration file or create separate configuration files under
/etc/nginx/conf.d/. Define oneserver { }block per domain. Each server block must specify a uniqueserver_namedirective that matches the domain name.
server {
listen 80;
server_name domain1.com www.domain1.com;
root /var/www/domain1.com;
index index.html index.php;
}
server {
listen 80;
server_name domain2.com www.domain2.com;
root /var/www/domain2.com;
index index.html index.php;
}Nginx matches incoming requests against each server block's
server_name value. The first matching server block handles the request. If no
server_name matches, Nginx uses the
default_server block.
- Test the nginx.conf configuration for syntax errors.
sudo nginx -t- Reload Nginx to apply the new server blocks without dropping active connections.
sudo systemctl reload nginxHow to Verify Multiple Domains Are Working
Nginx serves different content for each domain when the server blocks are configured correctly. Use
curl to check that each domain returns its expected content:
curl -I http://domain1.com
curl -I http://domain2.comEach response should show a
200 OK status and the correct
Content-Type header. Verify that the document root paths are correct by placing a unique
index.html file in each directory.
Common Issues When Hosting Multiple Domains in nginx.conf
DNS records not pointing to the server.Nginx can only serve domains whose DNS A records resolve to the server's IP address. Verify DNS resolution with
dig domain1.com A before troubleshooting Nginx configuration.
Missing default_server directive.Nginx assigns the first server block as the default when no
default_server is specified. Add
listen 80 default_server; to one server block to control which site handles unmatched requests.
File permission errors returning 403 Forbidden.Nginx requires read permissions on the document root and all parent directories. Set ownership to the Nginx user (typically
www-data) and use
755 for directories and
644 for files. See
Nginx: 403 Forbiddenfor detailed troubleshooting.