Adding VirtualHosts to Apache2


The first step is to decide how you want to name your file root. Below is an example that will work just fine.

    cd /var/www
    mkdir -p vhosts/domain.com/htdocs (this is where you will put your html.)
    mkdir -p vhosts/domain.com/log (this will be for your log files)
    chmod -R 755 vhosts/domain.com
Configuring NameVirtualHost

With virtual hosts, people often forget to configure NameVirtualHost.


For each port that Apache listens to, we need to define a NameVirtualHost. The issue that can catch people lies in the fact that you can only define it once per port.


In itself, that’s no problem but the default vhost has already defined a generic NameVirtualHost - adding another one will cause warnings and errors (and sometimes unexpected behavior).


The easiest thing to do is to remove the generic NameVirtualHost from the default vhost file and then add some specific ones to the main apache config file.


That way, if we ever delete or change the default vhost we don’t have to worry about where the NameVirtualHost setting is defined and so on.


OK. Let’s move into the apache directory and then open the default vhost:

    cd /etc/apache2/
    sudo nano sites-available/default

Delete the ‘NameVirtualHost *’ line and change the next ‘VirtualHost’ line so the file begins like this:

    <virtualhost *:80>
            ServerAdmin webmaster@localhost
            DocumentRoot /var/www/

Once that is done, we can open the main apache2.conf:

    nano apache2.conf

Make sure the following line is in the file and not commented out:

    Include /etc/apache2/sites-enabled/

Also make sure the following is in the file:

    NameVirtualHost *:80

    <ifmodule mod_ssl.c>
        NameVirtualHost *:443

If the above code is not in apache2.conf, I found that it would cause errors when the second vhost was enabled.


Let’s reload Apache now:

    sudo /etc/init.d/apache2 reload
Making A Custom Virtual Host

We’ve set up the basic structure and content, now we're ready to add this configuration to our webserver.


Let’s go ahead and create the configuration file for domain.com:

    nano /etc/apache2/sites-available/domain.com

The format of this file is very basic, you can view an example here:

    # Place any notes or comments you have here
    # Documenting changes helps track problems!
    # domain: domain1.com
    # public: /var/www/vhosts/domain.com/domain.com/
    <virtualhost *:80>
      # Admin email, Server Name (domain name) and any aliases
      ServerAdmin webmaster@domain.com
      ServerName  domain.com
      ServerAlias www.domain.com
      # Index file and Document Root (where the public files are located)
      DirectoryIndex index.html
      DocumentRoot /var/www/vhosts/domain.com/htdocs
      # Custom log file locations
      LogLevel warn
      ErrorLog  /var/www/vhosts/domain.com/log/error.log
      CustomLog /var/www/vhosts/domain.com/log/access.log combined