How To Use Apache Virtual Hosts for Your local Web Development Projects
I find it useful to have a local apache server set up for all my web-dev work so that i can see changes to files in real time, which makes it easier to develop server side web apps.
Up till a month or so ago i had been editing the DocumentRoot line in my /etc/httpd/httpd.conf every time i wanted to work on another project. This has slowly been driving me crazy so i decided to use virtual hosts to do all the dirty work for me.
Its basically a 5 step process:
1) ad new host file entries to point to localhost with the names you want
2) add new virtualhost directives for apache to show content for each of these names
3) restart apache
4) visit each of your new host entries in a browser
5) enjoy!
—-
First edit your /etc/hosts file to add a few new lines,
eg:
127.0.0.1 project1 127.0.0.1 project2
these are what we will be using to access our virtual hosts from now on.
The second step involves adding a few new virtual host directives to you /etc/httpd/httpd.conf file.
These tend to appear at the end of the httpd.conf file and should look like this.
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /Users/richie/Projects/project1
ServerName project1
</VirtualHost>
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /Users/richie/Projects/project2
ServerName project2
</VirtualHost>
The DocumentRoot line should point to your web dev folder that has you index file etc.
the Servername is whatever you set in the /etc/hosts file.
Now to just restart the httpd service and we are all finished.
# sudo apachectl restart
The final step is to test our new setup.
visit the virtual host name from your favorite web browser on the local machine, if you go to project1 it will show you the webroot for project1 and if you visit project2 it will show you the webroot for project2.
I use this these days to great effect, and it really is quite convenient.
NOTE:
This assumes that you have Web Sharing turned on in System Preferences > Sharing.