Multiple PHP versions under the same domain

I recently had cause to run two different versions of PHP under the same top-level domain. I was able to accomplish this using Apache and PHP-FPM, leveraging Apache’s Directory directive. This builds on DigitalOcean’s excellent tutorial, “How To Run Multiple PHP Versions on One Server Using Apache and PHP-FPM on Ubuntu 18.04”, and assumes that you have done something similar to get multiple versions of PHP running using PHP-FPM.

In my use case, I have multiple different version of Moodle running under the same top-level domain. Each Moodle version is installed in a different directory under that domain, and has its own uploads and database. Moodle is somewhat aggressive about supported PHP versions, and I needed to have both PHP 7.4 (for Moodle 3.9) and PHP 8.0 (for Moodle 4.1) available, and each cannot run under the other version.

The solution is to add an Directory override for the site that needs the lower version of PHP, while leaving the higher version as the default case:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<VirtualHost *:443>
ServerAdmin admin@example.net
ServerName foo.example.net
DocumentRoot /var/www/html/sites

ErrorLog ${APACHE_LOG_DIR}/foo-error.log
CustomLog ${APACHE_LOG_DIR}/foo-access.log combined

<Directory "/var/www/foo/sites/site1">
<FilesMatch \.php$>
SetHandler "proxy:unix:/run/php/php7.4-fpm-foo.sock|fcgi://foo/"
</FilesMatch>

</Directory>

<FilesMatch \.php$>
SetHandler "proxy:unix:/run/php/php8.0-fpm-foo.sock|fcgi://foo/"
</FilesMatch>

<Proxy "fcgi://foo/">
</Proxy>

</VirtualHost>

The specificity of the directory declaration for /var/www/foo/sites/site1 means that it will be served up using PHP 7.4, and everything else will use PHP 8.0.