How to Setup Multiple Domains in Same Directory in Apache


multiple domains in same directory in apache

Sometimes you are running multiple websites and want to serve the same website through multiple domains, without using any redirects. In such case, you can setup multiple domains from the same web root directory. Here’s how to setup multiple domains in same directory in Apache.

 

How to Setup Multiple Domains in Same Directory in Apache

Here are the steps to setup multiple domains in same directory in Apache.

Let’s say you want to set up 2 domains(www.domain1.com and www.domain2.com) in your Apache server running on same IP, same port and even the same web root directory.

 

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, ServerAlias but same DocumentRoot directives to setup multiple domains from same directory

 


NameVirtualHost *:80

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

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

 

The key is to specify different ServerName but same DocumentRoot in each virtual host.

 

If the above code doesn’t work for you, then you can try using ServerAlias directive


NameVirtualHost *:80

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


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 domains www.domain1.com and www.domain2.com will serve from the 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!