Update 1: An automated way doing all the stuff in this post is using VirtualHostX – you might want to try that out. It’s free for up to three vhosts – after that it costs money.
Update 2: Or even better: You can use the all free hostess. It’s pure command line and works great.
Today I wanted to test some PHP and MySQL using Apache in OS X but wasn’t able to find any guide on how to do this if I wanted multiple sites. So I might as well create my own:
cd /etc/apache2 sudo mkdir mysites # or whatever (I used my name, 'lasse', for the name) cd mysites sudo nano phptest.conf # or vi or whatever
Put the following in phptest.conf
:
<VirtualHost *:80> ServerName phptest.local DocumentRoot "/Users/yourname/dev/web/phptest" <Directory "/Users/yourname/dev/web/phptest"> Order allow,deny Allow from all </Directory> </VirtualHost>
Remember to replace yourname
for your username and to create the ~/dev/web/phptest
folder.
Back into the bash:
cd /etc/apache2 sudo nano httpd.conf
First find the lines that say:
#LoadModule php5_module libexec/apache2/libphp5.so #LoadModule fastcgi_module libexec/apache2/mod_fastcgi.so
And uncomment these two lines likes this:
LoadModule php5_module libexec/apache2/libphp5.so LoadModule fastcgi_module libexec/apache2/mod_fastcgi.so
This enables PHP.
Next, go to the bottom of the same file and add the following line:
Include /private/etc/apache2/mysites/*.conf
This tells Apache to also load configuration files from the mysites
folder.
Next, edit your hosts file to enable the phptest.local name:
sudo nano /etc/hosts
Add the following line at the bottom of the file:
127.0.0.1 phptest.local
This tells your DNS resolver to look for the site locally at your computer (127.0.0.1) when you type phptest.local in your browser.
It’s necessary to restart Apache to enable the new settings (you’ll need to do this every time you add a site).
sudo apachectl -k restart
Finally we create a test file to make sure it all works:
cd ~/dev/web/phptest nano test.php
Enter the following:
<?php echo "Hello World!" ?>
Now you should be able to go to http://phptest.local/test.php in your browser and it should say Hello World!
. If not, then something is wrong.
Adding a new site
Next time you want to add a site, just complete the following steps:
1. Create a site root folder in ~/dev/web/xx
or wherever you keep your sites.
2. Create a configuration file similar to phptest.conf
in /etc/apache2/mysites/
where you replace the paths and ServerName
for the new ones.
3. Create an entry in /etc/hosts
with the same name as you used as ServerName
.
4. Restart Apache using apachectl -k restart
.
Is there an easier way to do this? Please let me know in the comments.