How to Setup Multiple Virtual Hosts in Same Directory in NGINX


setup multiple virtual hosts in same directory in nginx

Sometimes, you may want to run multiple websites from same location, that is, you may want to point multiple domains to the same directory. You can easily do it with the help of virtual hosts. Here’s how to setup multiple virtual hosts in same directory in NGINX.

 

How to Setup Multiple Virtual Hosts in Same Directory in NGINX

Here are the steps to setup multiple virtual hosts in same directory in NGINX.

Before you proceed, please ensure that you have enabled virtual hosts in NGINX. Here are the steps to do it.

Let’s say you want to host 2 websites www.example.com and api.example.com on same IP.

 

1. Create Virtual Host Files

First, we create separate virtual host files – one for each domain. You can add the config for both websites in the same config file if you want. But this way it is cleaner and easier to manage.


$ sudo vim /etc/nginx/sites-available/www.example.com
$ sudo vim /etc/nginx/sites-available/api.example.com

 

2. Add Virtual Host Configuration

Add the following lines of code in the 2 files

#www.example.com


server {
 listen 80
 server_name www.example.com
 root /var/www/www.example.com/html; #also add a root dir here
 location / {
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_pass http://127.0.0.1:3836;
 }
}

 

 

#api.example.com


server {
 listen 80
 server_name api.example.com
 root /var/www/www.example.com/html; #also add a root dir here
 location / {
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_pass http://127.0.0.1:3836;
 }
}

 

The key is to differentiate the 2 configs with different server_name directive, but use the same root folder location for each website. Also make sure that they listen to the same port.

 

 

3. Enable the domains

Next, enable the 2 domains


$ sudo ln -s /etc/nginx/sites-available/www.example.com /etc/nginx/sites-enabled/www.example.com
$ sudo ln -s /etc/nginx/sites-available/api.example.com /etc/nginx/sites-enabled/api.example.com

 

 

4. Reload NGINX web server

Reload NGINX server to apply changes.

$ sudo service nginx reload

 

That’s it! NGINX will serve both your websites from same directory.

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!