How to Setup Multiple Virtual Hosts in Same IP in Apache


setup multiple virtual hosts in same ip in apache

If you run multiple websites, it might be worth configuring them on same IP, to save server costs and resources. You can easily do it with the help virtual hosts. Here’s how to setup multiple virtual hosts in same IP in Apache.

 

How to Setup Multiple Virtual Hosts in Same IP in Apache

Here are the steps to setup multiple virtual hosts in same IP in Apache.

Let’s say you want to set up 2 virtual hosts(www.domain1.com and www.domain2.com) in your Apache server running on same IP and same port, 80

 

1. Open Apache config file

Open Apache config file in a text editor. You will find it at one of the following locations:

  • /etc/apache2/httpd.conf
  • /etc/apache2/apache2.conf
  • /etc/httpd/httpd.conf
  • /etc/httpd/conf/httpd.conf

 


$ sudo vim /etc/apache2/httpd.conf

 

 

2. Add Virtual Hosts

We will use NameVirtualHost and ServerAlias directive to run both virtual hosts on same ip and port.

Add the NameVirtualHost directive.

Next, add 2 virtual host blocks, one for each virtual host , as shown. They both run on port 80. The key is to use different ServerName and ServerAlias directives and DocumentRoot directive to distinguish between the 2 virtual hosts. You can also use separate ErrorLog locations

 


NameVirtualHost *:80

<VirtualHost *:80>
 ServerName www.domain1.com
 DocumentRoot /var/www/html/domain1
 ErrorLog /var/log/apache2/domain1-error.log
</VirtualHost>

<VirtualHost *:80>
 ServerName www.domain2.com
 DocumentRoot /var/www/html/domain2
 ErrorLog /var/log/apache2/domain2-error.log
</VirtualHost>

 

The key is to specify different port names, ServerName and DocumentRoot in each virtual host.

 

Please Note: If you have setup separate virtual host files for each domain in Apache, then update the <VirtualHost> block in their respective files, with the ones shown above.

 

 

3. Restart Apache web server

Restart Apache web server to apply changes


$ sudo /etc/init.d/apache2 start [Debian or Ubuntu]
# sudo apachectl restart [RHEL, CentOS or Fedora]

 

That’s it! Now both virtual hosts www.domain1.com and www.domain2.com will serve from the same host

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!