Setting Up Apache Virtual Hosts

Apache is likely the most popular method of serving web content on the internet at the moment.  Chances are if you’re here (at my blog), you’re enough of a nerd to have heard of it before.  Basically Apache “compartmentalizes” its functionality and components if you will.  These “compartments” that are indicative of individual domains/websites are known as Virtual Hosts.  Once you have them (or just the one for starters) set up, you can set up all the websites you wish.

To begin, we need to install Apache.

After it finishes installing, we’re going to look at the Document Root under /var/www.  The Document Root is the top-level directory that Apache looks at to find content to serve, and is by default set to /var/www/html.  What we would like to do is make directories for the domains that we wish to serve.

We have created our Document Root directories but currently they are owned by root.  If you would like a sudo user that you have created to be owner do the following replacing sudouser with the account username.  Alternatively, you can use $USER:$USER and it will sub-in the value of the currently logged in user when you press enter.

 

Next we need to make sure that read access is allowed for our general web directory so that the webpages we plan to host can be served properly.

Now we’re going to move away from our Document Roots and switch gears to the Virtual Host Files.  Think of these as the recipe that the Apache engine follows when receiving a request.  These files specify the configuration of our virtual hosts and how the Apache web server will respond to domain requests.  These files are stored in /etc/apache2/sites-available.  By default Apache creates a Virtual Host File called 000-default.conf.  We are going to copy this to make our lives a little bit easier.

I personally like to keep everything named after the domain I’m using, but you can choose whatever naming scheme you would like.  Open the file in an editor with root privileges and you should get something like the following:

Obviously this information is a little generic and we want to customize it.  You’ll want to change the ServerAdmin and DocumentRoot values to match your virtual host.  You will also need (or may like to) add ServerName and ServerAlias.  You should have something like the following when you’re finished:

Save and close your file.  Now copy the newly customized Virtual Host File and sub out all the domain1.com for domain2.com, then save and close the file.

Now all that there is left to do is enable our new Virtual Hosts in Apache and some cleanup work.  Enable the Virtual Hosts with the following command:

Disable the Apache default site:

Finally, restart Apache to have all of our changes take effect: