Tutorial

How To Set Up Apache Virtual Hosts on Ubuntu 14.04 LTS

Published on April 22, 2014
English
How To Set Up Apache Virtual Hosts on Ubuntu 14.04 LTS
Not using Ubuntu 14.04?Choose a different version or distribution.
Ubuntu 14.04

Introduction

The Apache web server is the most popular way of serving web content on the internet. It accounts for more than half of all active websites on the internet and is extremely powerful and flexible.

Apache breaks its functionality and components into individual units that can be customized and configured independently. The basic unit that describes an individual site or domain is called a virtual host.

These designations allow the administrator to use one server to host multiple domains or sites off of a single interface or IP by using a matching mechanism. This is relevant to anyone looking to host more than one site off of a single VPS.

Each domain that is configured will direct the visitor to a specific directory holding that site’s information, never indicating that the same server is also responsible for other sites. This scheme is expandable without any software limit as long as your server can handle the load.

In this guide, we will walk you through how to set up Apache virtual hosts on an Ubuntu 14.04 VPS. During this process, you’ll learn how to serve different content to different visitors depending on which domains they are requesting.

Prerequisites

Before you begin this tutorial, you should create a non-root user as described in steps 1-4 here.

You will also need to have Apache installed in order to work through these steps. If you haven’t already done so, you can get Apache installed on your server through apt-get:

sudo apt-get update
sudo apt-get install apache2

After these steps are complete, we can get started.

For the purposes of this guide, my configuration will make a virtual host for example.com and another for test.com. These will be referenced throughout the guide, but you should substitute your own domains or values while following along.

To learn how to set up your domain names with DigitalOcean, follow this link. If you do not have domains available to play with, you can use dummy values.

We will show how to edit your local hosts file later on to test the configuration if you are using dummy values. This will allow you to test your configuration from your home computer, even though your content won’t be available through the domain name to other visitors.

Step One — Create the Directory Structure

The first step that we are going to take is to make a directory structure that will hold the site data that we will be serving to visitors.

Our document root (the top-level directory that Apache looks at to find content to serve) will be set to individual directories under the /var/www directory. We will create a directory here for both of the virtual hosts we plan on making.

Within each of these directories, we will create a public_html folder that will hold our actual files. This gives us some flexibility in our hosting.

For instance, for our sites, we’re going to make our directories like this:

<pre> sudo mkdir -p /var/www/<span class=“highlight”>example.com</span>/public_html sudo mkdir -p /var/www/<span class=“highlight”>test.com</span>/public_html </pre>

The portions in red represent the domain names that we are wanting to serve from our VPS.

Step Two — Grant Permissions

Now we have the directory structure for our files, but they are owned by our root user. If we want our regular user to be able to modify files in our web directories, we can change the ownership by doing this:

<pre> sudo chown -R $USER:$USER /var/www/<span class=“highlight”>example.com</span>/public_html sudo chown -R $USER:$USER /var/www/<span class=“highlight”>test.com</span>/public_html </pre>

The $USER variable will take the value of the user you are currently logged in as when you press “ENTER”. By doing this, our regular user now owns the public_html subdirectories where we will be storing our content.

We should also modify our permissions a little bit to ensure that read access is permitted to the general web directory and all of the files and folders it contains so that pages can be served correctly:

sudo chmod -R 755 /var/www

Your web server should now have the permissions it needs to serve content, and your user should be able to create content within the necessary folders.

Step Three — Create Demo Pages for Each Virtual Host

We have our directory structure in place. Let’s create some content to serve.

We’re just going for a demonstration, so our pages will be very simple. We’re just going to make an index.html page for each site.

Let’s start with example.com. We can open up an index.html file in our editor by typing:

<pre> nano /var/www/<span class=“highlight”>example.com</span>/public_html/index.html </pre>

In this file, create a simple HTML document that indicates the site it is connected to. My file looks like this:

<pre> <html> <head> <title>Welcome to <span class=“highlight”>Example.com</span>!</title> </head> <body> <h1>Success! The <span class=“highlight”>example.com</span> virtual host is working!</h1> </body> </html> </pre>

Save and close the file when you are finished.

We can copy this file to use as the basis for our second site by typing:

<pre> cp /var/www/<span class=“highlight”>example.com</span>/public_html/index.html /var/www/<span class=“highlight”>test.com</span>/public_html/index.html </pre>

We can then open the file and modify the relevant pieces of information:

<pre> nano /var/www/<span class=“highlight”>test.com</span>/public_html/index.html </pre> <pre> <html> <head> <title>Welcome to <span class=“highlight”>Test.com</span>!</title> </head> <body> <h1>Success! The <span class=“highlight”>test.com</span> virtual host is working!</h1> </body> </html> </pre>

Save and close this file as well. You now have the pages necessary to test the virtual host configuration.

Step Four — Create New Virtual Host Files

Virtual host files are the files that specify the actual configuration of our virtual hosts and dictate how the Apache web server will respond to various domain requests.

Apache comes with a default virtual host file called 000-default.conf that we can use as a jumping off point. We are going to copy it over to create a virtual host file for each of our domains.

We will start with one domain, configure it, copy it for our second domain, and then make the few further adjustments needed. The default Ubuntu configuration requires that each virtual host file end in .conf.

Create the First Virtual Host File

Start by copying the file for the first domain:

<pre> sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/<span class=“highlight”>example.com</span>.conf </pre>

Open the new file in your editor with root privileges:

<pre> sudo nano /etc/apache2/sites-available/<span class=“highlight”>example.com</span>.conf </pre>

The file will look something like this (I’ve removed the comments here to make the file more approachable):

<pre> <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> </pre>

As you can see, there’s not much here. We will customize the items here for our first domain and add some additional directives. This virtual host section matches any requests that are made on port 80, the default HTTP port.

First, we need to change the ServerAdmin directive to an email that the site administrator can receive emails through.

<pre> ServerAdmin <span class=“highlight”>admin@example.com</span> </pre>

After this, we need to add two directives. The first, called ServerName, establishes the base domain that should match for this virtual host definition. This will most likely be your domain. The second, called ServerAlias, defines further names that should match as if they were the base name. This is useful for matching hosts you defined, like www:

<pre> ServerName <span class=“highlight”>example.com</span> ServerAlias <span class=“highlight”>www.example.com</span> </pre>

The only other thing we need to change for a basic virtual host file is the location of the document root for this domain. We already created the directory we need, so we just need to alter the DocumentRoot directive to reflect the directory we created:

<pre> DocumentRoot /var/www/<span class=“highlight”>example.com</span>/public_html </pre>

In total, our virtualhost file should look like this:

<pre> <VirtualHost *:80> ServerAdmin <span class=“highlight”>admin@example.com</span> ServerName <span class=“highlight”>example.com</span> ServerAlias <span class=“highlight”>www.example.com</span> DocumentRoot /var/www/<span class=“highlight”>example.com</span>/public_html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> </pre>

Save and close the file.

Copy First Virtual Host and Customize for Second Domain

Now that we have our first virtual host file established, we can create our second one by copying that file and adjusting it as needed.

Start by copying it:

<pre> sudo cp /etc/apache2/sites-available/<span class=“highlight”>example.com</span>.conf /etc/apache2/sites-available/<span class=“highlight”>test.com</span>.conf </pre>

Open the new file with root privileges in your editor:

<pre> sudo nano /etc/apache2/sites-available/<span class=“highlight”>test.com</span>.conf </pre>

You now need to modify all of the pieces of information to reference your second domain. When you are finished, it may look something like this:

<pre> <VirtualHost *:80> ServerAdmin <span class=“highlight”>admin@test.com</span> ServerName <span class=“highlight”>test.com</span> ServerAlias <span class=“highlight”>www.test.com</span> DocumentRoot /var/www/<span class=“highlight”>test.com</span>/public_html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> </pre>

Save and close the file when you are finished.

Step Five — Enable the New Virtual Host Files

Now that we have created our virtual host files, we must enable them. Apache includes some tools that allow us to do this.

We can use the a2ensite tool to enable each of our sites like this:

<pre> sudo a2ensite <span class=“highlight”>example.com</span>.conf sudo a2ensite <span class=“highlight”>test.com</span>.conf </pre>

When you are finished, you need to restart Apache to make these changes take effect:

sudo service apache2 restart

You will most likely receive a message saying something similar to:

 * Restarting web server apache2
 AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1. Set the 'ServerName' directive globally to suppress this message

This is a harmless message that does not affect our site.

Step Six — Set Up Local Hosts File (Optional)

If you haven’t been using actual domain names that you own to test this procedure and have been using some example domains instead, you can at least test the functionality of this process by temporarily modifying the hosts file on your local computer.

This will intercept any requests for the domains that you configured and point them to your VPS server, just as the DNS system would do if you were using registered domains. This will only work from your computer though, and is simply useful for testing purposes.

Make sure you are operating on your local computer for these steps and not your VPS server. You will need to know the computer’s administrative password or otherwise be a member of the administrative group.

If you are on a Mac or Linux computer, edit your local file with administrative privileges by typing:

sudo nano /etc/hosts

If you are on a Windows machine, you can find instructions on altering your hosts file here.

The details that you need to add are the public IP address of your VPS server followed by the domain you want to use to reach that VPS.

For the domains that I used in this guide, assuming that my VPS IP address is 111.111.111.111, I could add the following lines to the bottom of my hosts file:

<pre> 127.0.0.1 localhost 127.0.1.1 guest-desktop 111.111.111.111 <span class=“highlight”>example.com</span> 111.111.111.111 <span class=“highlight”>test.com</span> </pre>

This will direct any requests for example.com and test.com on our computer and send them to our server at 111.111.111.111. This is what we want if we are not actually the owners of these domains in order to test our virtual hosts.

Save and close the file.

Step Seven — Test your Results

Now that you have your virtual hosts configured, you can test your setup easily by going to the domains that you configured in your web browser:

<pre> http://<span class=“highlight”>example.com</span> </pre>

You should see a page that looks like this:

Apache virt host example

Likewise, if you can visit your second page:

<pre> http://<span class=“highlight”>test.com</span> </pre>

You will see the file you created for your second site:

Apache virt host test

If both of these sites work well, you’ve successfully configured two virtual hosts on the same server.

If you adjusted your home computer’s hosts file, you may want to delete the lines you added now that you verified that your configuration works. This will prevent your hosts file from being filled with entries that are not actually necessary.

If you need to access this long term, consider purchasing a domain name for each site you need and setting it up to point to your VPS server.

Conclusion

If you followed along, you should now have a single server handling two separate domain names. You can expand this process by following the steps we outlined above to make additional virtual hosts.

There is no software limit on the number of domain names Apache can handle, so feel free to make as many as your server is capable of handling.

<div class=“author”>By Justin Ellingwood</div>

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
10 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Update: Glad to report that all is well and working fine. Had to run a2dissite 000-default then service apache2 restart

All is good now :)

Andrew SB
DigitalOcean Employee
DigitalOcean Employee badge
April 24, 2014

@michaelleblanc1: It sounds like you are on a different Ubuntu release, perhaps 12.04. This tutorial is specifically talking about 14.04 where the file has been renamed from simply “default” to “000-default.conf” Assuming that you are on 12.04, you should be fine, but you might also want to take a look at this article:

https://www.digitalocean.com/community/articles/how-to-set-up-apache-virtual-hosts-on-ubuntu-12-04-lts

Here’s a quick script that will make this easy and painless. Let’s say we call it “addsite” - place in /bin and call like this:

addsite yourdomain.com

Hope this helps!

#!/bin/bash

mkdir -p /var/www/$1/public_html 
chown -R $USER:$USER /var/www/$1/public_html 
chmod -R 755 /var/www 

cp /etc/apache2/sites-available/default /etc/apache2/sites-available/$1 

text="<VirtualHost *:80>
        ServerAdmin YOURNAME@YOURHOST.com
        ServerName $1
        ServerAlias www.$1
        DocumentRoot /var/www/$1/public_html
        <Directory />
                Options FollowSymLinks
                AllowOverride All
        </Directory>
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>"

echo "$text" > /etc/apache2/sites-available/$1 

a2ensite $1 
service apache2 reload

I also had to specify <directory /var/www/test.com/public_html/> Require all granted </directory>

in the conf file as per http://httpd.apache.org/docs/2.4/upgrading.html

Thanks for this great tutorial. My primary virtual host (ie example.com) is alive and well.

My droplet’s ip address still points to /var/www/html though and provides the “Apache2 Ubuntu Default Page”. I would like my ip to point to the new virtual host I created and hence to /var/www/test.com/public_html. How can I achieve this result?

Thank you.

www.exampe.dev’s server IP address could not be found. How can i fix this error.

To access http://example.com you need to have a domain bought and setup to point to the VPS IP address right?

Hello,

I originally have a wordpress site installed on my droplet. After following all the steps here, I’m now stuck at being shown the image in step 7. How do I change my preferences so that I can go back to seeing my wordpress site when I enter that domain in my browser?

Thank you!

UPDATE: Fixed it- just moved my old html file to under thecollegedorm.com, remove public_html, rename old html file to public_html.

Hello! The tutorial is clear to me and I have a bit of experience on this kind of configuration, but when I try to visit example.com, after all the configuration the page return a “ERR_CONNECTION_TIMED_OUT”. My droplet is an Ubuntu 16.04.4, what I’m doing wrong? Thank you for support!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.