Host multiple domains in Nginx

Host multiple domains in Nginx

By default, Nginx on Ubuntu 16.04 has one server block enabled by default. It is configured to serve documents at /var/www/html.

To serve multiple sites/domains. We need to do the following:

Create directories

We need to create these directories for each of our domains:

1
2
3
4
5
sudo mkdir -p /var/www/DOMAIN-1.com/html
sudo mkdir -p /var/www/DOMAIN-2.com/html
sudo chown -R $USER:$USER /var/www/DOMAIN-1.com/html
sudo chown -R $USER:$USER /var/www/DOMAIN-2.com/html

Create Server Block Files for Each Domain

File: /etc/nginx/sites-available/DOMAIN-1.com

1
2
3
4
5
6
7
8
9
10
11
12
13
14
server {
listen 80;
listen [::]:80;
root /var/www/DOMAIN-1/html;
index index.html index.htm;
server_name www.DOMAIN-1.com;
location / {
try_files $uri $uri/ =404;
}
}

File: /etc/nginx/sites-available/DOMAIN-2.com

1
2
3
4
5
6
7
8
9
10
11
12
13
14
server {
listen 80;
listen [::]:80;
root /var/www/DOMAIN-2/html;
index index.html index.htm;
server_name www.DOMAIN-2.com;
location / {
try_files $uri $uri/ =404;
}
}

Run:

1
2
sudo ln -s /etc/nginx/sites-available/DOMAIN-1.com /etc/nginx/sites-enabled/
sudo ln -s /etc/nginx/sites-available/DOMAIN-2.com /etc/nginx/sites-enabled/

In order to avoid a possible hash bucket memory problem while adding additional server names, modify /etc/nginx/nginx.conf.

1
sudo nano /etc/nginx/nginx.conf

Uncomment this line:

1
server_names_hash_bucket_size 64;

Test:

1
sudo nginx -t

Restart Nginx:

1
sudo systemctl restart nginx

Add hosts

1
sudo nano /etc/hosts
1
2
YOUR_IP www.DOMAIN-1.com
YOUR_IP www.DOMAIN-2.com
Share