Set Up Name-Based Virtual Hosts In Apache

If your server has only one IPĀ  (or even if you have many) and you want to host different websites you can use Apache’s name-based virtual hosts feature.

Setting up name-based virtual hosts is easy. First, open up httpd.conf found in the conf directory of your Apache installation directory.

First, you need to enable name-based virtual hosting. Make sure to uncomment the line that does this:

NameVirtualHost *:80

If your server has multiple IPs you can choose which IP will host name-based virtual hosts

NameVirtualHost 10.0.0.1:80

Now you can define different sites for every DNS name your server has. Just add the following for every name:

<VirtualHost 10.0.0.1:80>
   ServerAdmin [email protected]
   DocumentRoot /www/docs/www.example.com
   ServerName www.example.com
   ServerAlias www2.example.com www3.example.com
   ErrorLog logs/www.example.com-error_log
   CustomLog logs/www.example.com-access_log common
</VirtualHost>

ServerName is the required for the first DNS name. For additional DNS names corresponding to the same virtual host, you can use ServerAlias and add as many DNS names you want separated by spaces.

Don’t forget you can mix and match IPs and ports as in IP-based virtual hosts.

Save and restart Apache.

That’s it!