24 July 2013

How To: Set Up Apache Virtual Hosts on Ubuntu 12.04

Virtual Hosts are used to run more than one domain on a single IP address. This is especially useful to people who need to run several sites on one virtual private server.

1. Create a New Directory where we will keep the new website’s information


sudo mkdir -p /var/www/example.com/public_html


2. Grant Permissions of the directory to the user


sudo chown -R $USER:$USER /var/www/example.com/public_html 

Additionally, make sure that everyone will be able to read the files.

sudo chmod -R 755 /var/www

3. Create the Page


sudo nano /var/www/example.com/public_html/index.html

Example:
<html>
  <head>
    <title>Domain: www.example.com</title>
  </head>
  <body>
    <h1>My Virtual Host</h1>
  </body>
</html>

4. Create the New Virtual Host File


sudo cp /etc/apache2/sites-available/default /etc/apache2/sites-available/example.com

5. Turn on Virtual Hosts


sudo nano /etc/apache2/sites-available/example.com

We are going to set up a virtual host in this file.

The first step is to insert a line for the ServerName under the ServerAdmin line.

ServerName example.com 

The ServerName specifies the domain name that the virtual host uses.

If you want to make your site accessible from more than one name, for example with www in the URL, include the alternate names in your virtual host file by adding a ServerAlias Line. The beginning of your virtual host file would then look like this:

<VirtualHost *:80>
        ServerAdmin webmaster@example.com
        ServerName example.com
        ServerAlias www.example.com
[...]

6. Fill in the correct Document Root


DocumentRoot /var/www/example.com/public_html

7. Activate the host


sudo a2ensite example.com

8. Restart Apache


sudo service apache2 restart

You are done!

If you see messages like:
Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName
Just ignore them.

Good Luck!

----------------

No comments: