These days, with evolving hardware, it is more cost efficient to host multiple web servers on one service.
Together with improving software, such thing can be easily achieved.
I am describing in this article how to create 2 virtual hosts named test1.com and test2.com.
Virtual Host in Apache 2.4
I am using for Apache 2.4 for virtual host.
Create root directory
Typically web contents are served from files under
/var/wwwin linux.You can add subdirectory under it to create separate document root for each virtual host.
How I do it is by creating directory
wwwunder/srvand create another sub-directories for each virtual host.eg.
#> cd /srv #> mkdir www #> mkdir www/test1 #> mkdir www/test2Add content to document root
#> nano /srv/www/test1/index.html #> nano /srv/www/test2/index.htmlDefine virtual host in apache config file
Apache 2.4 will generate server(s) by referencing config files under
/etc/apache2/sites-enabled/, however, as a rule of thumb, you should create a config file under/etc/apache2/sites-available/and once it’s complete, generate a symbolic link.#> nano /etc/apache2/sites-available/testserver.conf #> cd /etc/apache2/sites-enabled/ #> ln -s ../sites-available/testserver.conf testserver.confThe content of
testserver.confwill look like below:<VirtualHost *:80> ServerName test1.com DocumentRoot /srv/www/test1 </VirtualHost> <VirtualHost *:80> ServerName test2.com DocumentRoot /srv/www/test2 </VirtualHost>4 lines are enough to create the Virtual Host!
Essential to be wrapped within
directive is: - ServerName: specifies what hostname must appear in the request’s
Host:header to match this virtual host. It can be omitted so it will be the last resort host. - DocumentRoot: identifies where the document is served from
Optionally you can add more directives to control the accesses / redirect / alias, etc.
- ServerName: specifies what hostname must appear in the request’s
Map the domain to the virtual hosts
In my example, I am hosting a server to my self. So am modifying
hostsfile to be able to recognise the virtual host.#> cat /etc/hosts 127.0.0.1 localhost test1.com test2.com ...When you make it public, you modify the A record of your domain provider.
Test it
Now you can wget or curl it to test it out!
wget -O - http://test1.com
That’s it!