How to Setup Multiple Domains on Same IP in NGINX


multiple domains on same ip in nginx

If you are running multiple websites, you might want to serve them from same server/IP to save server costs and resources. Let us take a look at how to setup multiple domains on same IP in NGINX.

 

How to Setup Multiple Domains on Same IP in NGINX

Here are the steps to setup multiple domains on same IP 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.domain1.com and www.domain2.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.domain1.com
$ sudo vim /etc/nginx/sites-available/www.domain2.com

 

2. Add Virtual Host Configuration

Add the following lines of code in the 2 files

#www.domain1.com


server {
 listen 80
 server_name www.domain1.com
 root /var/www/www.domain1.com/html/domain1/app; #also add a root dir here
 location / {
  ...
 }
}

 

 

#www.domain2.com


server {
 listen 80
 server_name www.domain2.com
 root /var/www/www.domain2.com/html/domain2/app; #also add a root dir here
 location / {
  ...
 }
}

 

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

If you want both the domains to serve the same file, you can simply place the 2 website names one beside the other  in a single server block and use a single root directive, as shown below


server {
 listen 80
 server_name www.domain1.com www.domain2.com
 root /var/www/www.domain.com/html/domain/app; 
 location / {
   ...
 }
}

 

 

3. Enable the domains

Next, enable the 2 domains


$ sudo ln -s /etc/nginx/sites-available/www.domain1.com /etc/nginx/sites-enabled/www.domain1.com
$ sudo ln -s /etc/nginx/sites-available/www.domain2.com /etc/nginx/sites-enabled/www.domain2.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 IP.

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!