How to Host Multiple Domains on One Server in NGINX

NGINX allows you to host multiple websites on a single server with the help of virtual hosts. Each virtual host handles a website domain and serves requests from its own Document Root folder. When a request is made to one of the websites hosted on NGINX server, the virtual host matching the domain name in requested URL will serve the request. In this article, we will look at how to host multiple domains on one server in NGINX.


How to Host Multiple Domains on One Server in NGINX

Here are the steps to host multiple domains on one server in NGINX. In our example, we will host 2 domains example1.com and example2.com.


1. Create Document Root Directories

We will create 2 separate document root folders, one for each domain.

$ sudo mkdir /var/www/html/example1.com
$ sudo mkdir /var/www/html/example2.com

Requests to example1.com will be served from resources present in /var/www/html/example1.com subfolder and those to example2.com will be served from /var/www/html/example2.com.

Also read : How to Uninstall NGINX from Ubuntu


2. Create index.html files

Next we will create index.html files for each of the websites.

Run the following command to create index.html file for example1.com website.

$ sudo vi /var/www/html/example1.com/index.html

Add the following lines to it.

<html>
<title>www.example1.com</title>
<h1>Welcome to www.example1.com Website</h1>
</html>

Save and close the file.

Also read : How to Exclude Files in Git Commit

Similarly, run the following command to create index.html file for example2.com website

$ sudo vi /var/www/html/example2.com/index.html

Add the following lines to it.

<html>
<title>www.example2.com</title>
<h1>Welcome to www.example2.com Website</h1>
</html>

Save and close the file.


3. Open NGINX configuration file

Open NGINX configuration file at /etc/nginx/nginx.conf

$ sudo vi /etc/nginx/nginx.conf

Also read : How to Save Iptables Rules Permanently


4. Create Server blocks

We need to create 2 server blocks, one for each domain, as shown below. Replace the values for server_name and root as per your domain names and document root locations respectively.

server {
listen 80;
   root /var/www/html/example1.com;
   index index.html;
   server_name example1.com;
   location / {
       try_files $uri $uri/ =404;
   }
}

server {
   listen 80;
   root /var/www/html/example2.com;
   index index.html;
   server_name example2.com;
   location / {
       try_files $uri $uri/ =404;
   }
}

Also read : How to Convert String to UTF8 in Python


5. Restart NGINX Server

Restart NGINX server to apply changes.

$ sudo nginx -t 
$ sudo systemctl restart nginx

That’s it. Now open browser and go to http://example1.com. You will see the index page for example1.com

Similarly, open browser and go to http://example2.com. You will see the index page for example2.com

That’s it. Now you will be able to access both your websites hosted on one server.