Adding Virtual Host to Apache in Ubuntu

Now that I have Ubuntu installed on my computer and the Apache web server is working. I need to configure a virtual host. Right after you get Apache going, it defaults to serving from a default location, in this case /var/www. Any http requests coming into the box are all routed to that directory.

But Apache supports multiple hosts and I want to add one virtual host to Apache so that if I route say example.com to my IP, I want it to be served from its own directory. The default /var/www has system ownership and would need to be changed. So I’m going to create a directory for example.com site under my user directory. So I’ll create /home/rashid/htdocs/example to host the files for this site.

Step 1: create /home/rashid/htdocs/example to host the files for this site.

Now we need to make Apache use them. In the default configuration, Apache is already set up to support multiple virtual Hosts. In order to get the new sites working, we need to create a couple of configuration files in the /etc/apache2/sites-available directory, then enable them, and then restart Apache.

If you look in the sites-available, you’ll find a file called default. This represents the default Apache serving configuration. Copy this file twice to serve as a basis for the new configuration files.

Step 2: cd /etc/apache2/sites-available
sudo cp default example

You need to make two or three changes to this file, and add one line.

Step 3: Put your email address against ServerAdmin. If you want, you can make the value a real e-mail address.

Step 4: There are also two lines labelled DocumentRoot and another in a <Directory> statement that have the path to the directory being served – in this case, it should be /var/www/. Change both of those to the directory that will contain the new site files – /home/rashid/htdocs/example/.

Step 5 : Now after the ServerAdmin line add a new line:
ServerName example.com

Step 6: If you want to have nickname of your host then add a new line after ServerName:
ServerAlias www.example.com

Now we have to tell Apache to serve the new domains. Ubuntu has a couple of convenience commands to enable and disable sites.

Step 7: So, to enable the new sites, enter sudo a2ensite example1 . This command copy the configuration files you created into the /etc/apache2/sites-enabled directory. We’re almost there.

Finally, you have to restart Apache2 so that it reconfigures to serve the new sites.

Step 8: Simply enter sudo /etc/init.d/apache2 reload.

Now we are done with the virtual host configuration in easy 8 steps.

One thought on “Adding Virtual Host to Apache in Ubuntu

Leave a Reply

Your email address will not be published. Required fields are marked *