Virtual hosts with Apache
Apache offers the possibility to define virtual hosts. For me as developer this is good to host all my different projects and test projects on one single Apache web server. For my local work, I use XAMPP for Mac. This article can also be used for other operating systems or real Apache installations.
Normally you add projects or applications by copying their code to ‚htdocs‘ directory of you XAMPP installation. There is already an example installed (webalizer). With a running Apache, you can access the applications with a browser. For example your webalizer tool can be started with localhost/webalizer. If you want to test an application, simply copy the source code into the directory and you can view it in your browser.
- simple and fast
- no configuration needed
- all projects are reached only under localhost
- copy your code every time it changes or create a link
To configure a virtual host we take a look into your ‚etc‘ directory of XAMPP. The file ‚httpd.conf‘ is a global configuration file for your Apache. For some projects you might want to change things here. You can for example activate or deactivate modules. In the ‚extra‘ directory there are many configuration files. On of it is ‚httpd-vhosts.conf‘ for virtual hosts. It is a good idea to copy the file before we make changes.
If you open the file you see, that there is already a virtual host called ‚localhost‘ defined. Yes, localhost is also a virtual host! Don’t change it. To add new virtual hosts, just add code at the end of the file. The following code defines a new host:
Allow from All
The configuration is quite simple. You have to define following things:
this is the name of our host. The application can be viewed under ‚MyTestApp‘ in your Browser.
this is the root directory of your application. The place where all source code is stored. In this example it is my OSX home directory./li>
normally index.php or index.html file which will be displayed to the user.
you can also define access privileges for this directory.
After rebooting you Apache the application should be displayed when you enter ‚MyTestApp‘ in your browser. But nothing happens. It takes me some time to find the problem, but the solution is very simple. Your computer does not know the hostname. You simply have to add the name of your virtual host to your ‚hosts‘ file of your operating system. This can be different from system to system. For unix systems (Linux or OSX) it is the ‚/etc/hosts‘. There you have to add the following line:
Now your virtual host is ready!