Saturday, March 12, 2011

Setting up a Virtual Host in Apache 2 on Linux (Ubuntu)

When you install Apache on your Linux computer, it is configured to treat all files in "/var/www" as the web root by default. To run a website locally on your machine, you could copy all files into this directory. However, this is not the best way to go if you are doing serious development work, such as designing multiple websites on the same computer.

What you should do is create a virtual host. This allows you to store your website files anywhere you want:

1. Configure Apache
First, you have to add a virtual host to Apache. At least on my distro (Ubuntu), Apache splits its configuration settings into multiple files for organizational purposes. The "apache2.conf" file is the "root" file and imports all the other files. Virtual hosts are defined in the "/etc/conf/apache2/sites-enabled" directory, each inside their own file. The name of the file does not matter. Create a new file in this directory and enter the following text, replacing paths where necessary:

<Directory "/home/michael">
 Order Deny,Allow
 Allow from all
</Directory>

NameVirtualHost  127.0.0.1

<VirtualHost 127.0.0.1>
 DocumentRoot "/home/michael/testhost"
 ServerName testhost.local
</VirtualHost>

The "ServerName" will be the URL you use to access your website. ".local" is a naming convention used in the industry for running websites locally.

Apache must always be restarted whenever you change its conf settings:
sudo service apache2 restart
Tip: In order to edit these files, you have to open them as root. Using a command-line text editor can be cumbersome, especially if you need to have multiple files open at once. Instead, just open up a GUI text editor as the root user. For example:
sudo gedit &
2. Edit hosts file
Next, edit your host file. On Linux, this is located at "/etc/hosts". Add the following line at the end, replacing "testhost.local" with the "ServerName" parameter in the Apache conf file.:

127.0.0.1 testhost.local

This will tell your browser to access this URL from your local machine, instead of trying to find it out on the Internet.
Tip #2: In Linux, it can be hard to remember the locations of all these configuration files, especially because they can change depending on the distro. Any time you come across a new config file you haven't seen before, store its location in a centralized place, such as in a text file in your home folder. That way, you'll know exactly where to find it the next time you need it.
3. File permissions
Make sure the folder and all files in it are globally readable. Otherwise, Apache will not be able to see them and you will get "Forbidden" errors.

chmod -R 744 /home/michael/testhost

1 comment:

lauren said...

I came across a project where I needed to setup a virtual host in Apache 2 on Linux and as I searched on Google I found your blog.Thanks for such a wonderful article.It really save my time.
digital signature certificate