easily creating name based virtual hosts in apache

Check if your /etc/apache2/ports.conf has following two lines

NameVirtualHost *:80
Listen 80

Create two directories in /var/www
# mkdir /var/www/{foo,bar}

These two directories in /var/www/ will serve as a document root for our two test sites foo.com and bar.com respectively

Create index.html file in each of these two directories and put some html code in it.
I am foo.com
I am bar.com

Put entries in /etc/hosts
You need to also put 2 entries in your /etc/hosts file since we are testing it on localhost. If you are doing it on a server then make sure you have respective A records in DNS.
Open /etc/hosts in your favourite editor and put following two entries at the bottom of the file without disturbing original contents of file foo.com foo bar.com bar

Just make sure that above IPs are not already in use in same file …if any of them is in use, then for your entries you can
use any IP in 127.x.x.x range.

Create virtual hosts
Now create two files, “foo.com” and “bar.com” in /etc/apache2/sites-available/
Contents of foo.com

ServerName foo.com
ServerAlias http://www.foo.com
DocumentRoot /var/www/foo/

Similarly create bar.com with following content

ServerName bar.com
ServerAlias http://www.bar.com
DocumentRoot /var/www/bar/

Enable newly created sites
# a2ensite foo.com bar.com

Reload Apache
# service apache2 reload OR # /etc/init.d/apache2 reload

Open your browser and put “foo.com” in address bar .. you should be able to see the contents of /var/www/foo/index.html file
Repeat same step for “bar.com” as well to confirm that your setup is working



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s