This page looks best with JavaScript enabled

Apache2.4 Virtual Host

 ·  β˜• 2 min read  ·  🐨 Puliyo

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.

  1. Create root directory

    Typically web contents are served from files under /var/www in linux.

    You can add subdirectory under it to create separate document root for each virtual host.

    How I do it is by creating directory www under /srv and create another sub-directories for each virtual host.

    eg.

    #> cd /srv
    #> mkdir www
    #> mkdir www/test1
    #> mkdir www/test2
    
  2. Add content to document root

    #> nano /srv/www/test1/index.html
    #> nano /srv/www/test2/index.html
    
  3. Define 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.conf
    

    The content of testserver.conf will 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.
    4. Map the domain to the virtual hosts

    In my example, I am hosting a server to my self. So am modifying hosts file 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.

  4. Test it

    Now you can wget or curl it to test it out!

    wget -O - http://test1.com

That’s it!

Share on