Saturday, 30 June 2012

Set Virtual Hosts for XAMPP in Windows

By Default we put our code in htdocs folder in XAMPP. And url of our every site starts with localhost. This is not a good example of coding and can cause problems in Hard Coded codes and server side includes.

Virtual Host is used to host more than one Web site and domain on our local machine. We can give whatever name we want to our local Web site like http://local.abc.com or http://local.xyz.com.
To achieve this we simply have to make entries in two files in XAMPP. Also it is not necessary to store our code in htdocs folder than. We can put our code anywhere and can make DocumentRoot entry in httpd-vhosts.conf file.

Setting Virtual host is a two step process similar to Linux
1. Open C:\xampp\apache\conf\extra\httpd-vhosts
  Make below written entry in the end. All other lines are already commented and explanation is give there also.
NameVirtualHost *
  <VirtualHost *>
    DocumentRoot "C:\xampp\htdocs"
    ServerName localhost
  </VirtualHost>
  <VirtualHost *>
    DocumentRoot "C:\xampp\htdocs\local-site"
    ServerName local.abc.com
  <Directory "C:\xampp\htdocs\local-site">
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

Subsequent sites can be added by adding below entry for each new site
<VirtualHost *>
    DocumentRoot "C:\xampp\htdocs\local-site-two"
    ServerName local.xyz.com
  <Directory "C:\xampp\htdocs\local-site-two">
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

DocumentRoot can be changed in the following way
<VirtualHost *>
    DocumentRoot "D:\work\new-site-three"
    ServerName local.newsite.com
  <Directory "D:\work\new-site-three">
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

2. Open C:\WINDOWS\system32\drivers\etc\hosts
At the end of file make enteries of each site in the following way
127.0.0.1       local.abc.com
127.0.0.1       local.xyz.com
127.0.0.1       local.newsite.com

That's all is needed to set virtual hosts in windows. Remember to restart Apache after making these changes.
If you face any issues with setting virtual host path than do let me know.

More information on www.narendrarathore.com