Apache Virtual Hosts: A Clean Setup for (PHP-)Developers

posted in: apache, linux, php | 0

If you work on multiple Apache-based Web projects in parallel you probably know this problem: You have to set up a virtual host configuration for every single project on your development machine. It would be very nice to reduce the steps required for this to a minimum. My favorite solution:
Have a directory in your home directory containing symbolic links to your projects – where the names of the links are your local host names.

The following instructions assume you’re on Debian/Ubuntu – but “translating” them to other distros or even Windows shouldn’t be that hard.

Install Required Packages

You need to have the following packages installed:

  • libapache2-mod-fcgid: My preferred FastCGI module
  • apache2-suexec-custom: Let’s your FastCGI script run under a custom user account. No more “chmod 777” or “chown www-data…” in your home directory!
  • apache2-mpm-worker: The threaded MPM of apache – mod_suexec depends on it.

Install those packages on Debian/Ubuntu:

sudo apt-get install apache2-mpm-worker apache2-suexec-custom apache2-mod-fcgid

And enable the required modules:

sudo a2enmod actions
sudo a2enmod fcgid
sudo a2enmod suexec
sudo a2enmod vhost_alias

Create the Apache Config

Now create the file /etc/apache2/sites-available/my-vhosts and replace “steffen” with your account name:

<VirtualHost *:80>

  LogFormat "%V %h %l %u %t \"%r\" %s %b" vcommon
  CustomLog /var/log/apache2/my-vhosts_access.log vcommon

  SuexecUserGroup steffen steffen

  VirtualDocumentRoot /home/steffen/vhosts/%0/
  VirtualScriptAlias /home/steffen/vhosts/cgi-bin/

  AddHandler php-fcgi .php
  Action php-fcgi /cgi-bin/php5.fcgi

  <Directory /home/steffen>
    Order Deny,Allow
    Allow from all
    Options -Indexes FollowSymLinks ExecCGI
    AllowOverride All
  </Directory>

</VirtualHost>

As you can see this file refers to the directory /home/steffen/vhosts – let’s create it …

mkdir -p ~/vhosts/cgi-bin

… and our PHP FastCGI-Wrapper ~/vhosts/cgi-bin/php5.fcgi:

#!/bin/sh
exec /usr/bin/php5-cgi

On Debain/Ubunut you also need to configure suexec-common. Put the following lines to the file /etc/apache2/www-data:

/home/steffen
/var/www
public_html/cgi-bin

Enable your site and restart Apache – you may have to disable the default vhost on Debian/Apache:

sudo a2ensite my-vhosts
sudo a2dissite default
sudo /etc/init.d/apache2 restart

Add a Virtual Host

Let’s assume you have a PHP project, e.g. WordPress, Drupal, etc., in the directory ~/myprojects/php/my-wordpress-blog. All you have to do in order to give it a local virtual hosts is the following:

ln -s ~/myprojects/php/my-wordpress-blog ~/vhosts/blog.local
sudo nano -w /etc/hosts

… and append the following line to /etc/hosts

127.0.1.1   blog.local

That’s it – you’re ready to navigate to http://blog.local with your favorite browser 🙂