chungn

Streamlining Multiple PHP Projects with Apache Virtual Hosts

As a PHP developer, I often find myself working on multiple projects, each requiring a different PHP version. In the past, setting up each project involved creating a new Apache (or Nginx) configuration file and adding an entry to my /etc/hosts file. While this process isn’t overly complex, I’ve always been on the lookout for ways to optimize it. After some exploration and experimentation, I’ve found a solution that eliminates the need for separate configurations for each project.

Dynamic Virtual Hosts with Apache

I achieved this by using a dynamic Apache virtual host configuration, which simplifies project setup. The configuration are as follows:

<VirtualHost *:80>
    ServerAlias *.php81
    VirtualDocumentRoot /var/www/html/%2/%1

    <IfModule dir_module>
        DirectoryIndex index.html
    </IfModule>

    ###
    # %1 is first group captured by RewriteCond (matched against %{HTTP_HOST} eg: "public.example.php81")
    # $1 is first group captured by RewriteRule (matched against eg: "/app1/index.html")
    # Reference: https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html
    ###
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^([^.]+).([^.]+).php81$ [NC]
    RewriteRule ^\/(.*\.php(\/.*)?)$ fcgi://php81:9000/var/www/html/%2/%1/$1 [P]
</VirtualHost>

As you can easily see from this config, there are 3 differences from a normal/simple virtual host config:

Note: While this configuration is fantastic for development purposes, it may not be suitable for a production environment due to potential performance issues.

To complete this setup, you’ll need to use a tool like dnsmasq, which I may cover in a future post.

By implementing this dynamic virtual host configuration, you can streamline your workflow and eliminate the need for separate Apache configurations for each project, making PHP development more efficient and enjoyable.