When managing multiple websites on a server, each requiring a different PHP version, you can configure Apache to support multiple PHP versions. This guide will walk you through the process of installing PHP 7.4 and PHP 8.1, configuring virtual hosts, and enabling FastCGI processing for each version on server.
Step 1: Install PHP 7.4 and PHP 8.1
Start by updating your package list and installing the necessary dependencies:
sudo apt update
sudo apt install -y lsb-release apt-transport-https ca-certificates wget
Next, add the PHP repository from Sury, which provides up-to-date PHP versions:
wget -qO - https://packages.sury.org/php/apt.gpg | sudo apt-key add -
echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" | sudo tee /etc/apt/sources.list.d/php.list
Update your repositories and install PHP 7.4 and 8.1 with essential modules:
sudo apt update
sudo apt install -y php7.4 libapache2-mod-php7.4 php7.4-{common,mbstring,xmlrpc,soap,gd,xml,intl,mysql,cli,zip,curl}
sudo apt install -y php8.1 libapache2-mod-php8.1 php8.1-{common,mbstring,xmlrpc,soap,gd,xml,intl,mysql,cli,zip,curl}
Step 2: Enable Both PHP Versions in Apache
Enable the necessary PHP modules for both versions:
sudo a2enmod php7.4
sudo a2enmod php8.1
Restart Apache to apply the changes:
sudo systemctl restart apache2
Step 3: Configure Virtual Hosts for Different PHP Versions
For each website, you can specify the PHP version to use by configuring virtual hosts. Here's how to set up two virtual hosts:
Site using PHP 7.4: Create a configuration file /etc/apache2/sites-available/site1.conf:
<VirtualHost *:80>
ServerName site1.example.com
DocumentRoot /var/www/site1
<FilesMatch \.php$>
SetHandler "proxy:unix:/var/run/php/php7.4-fpm.sock|fcgi://localhost/"
</FilesMatch>
ErrorLog ${APACHE_LOG_DIR}/site1-error.log
CustomLog ${APACHE_LOG_DIR}/site1-access.log combined
</VirtualHost>
Site using PHP 8.1: Similarly, create another configuration file /etc/apache2/sites-available/site2.conf:
<VirtualHost *:80>
ServerName site2.example.com
DocumentRoot /var/www/site2
<FilesMatch \.php$>
SetHandler "proxy:unix:/var/run/php/php8.1-fpm.sock|fcgi://localhost/"
</FilesMatch>
ErrorLog ${APACHE_LOG_DIR}/site2-error.log
CustomLog ${APACHE_LOG_DIR}/site2-access.log combined
</VirtualHost>
Step 4: Enable Virtual Hosts and Required Apache Modules
Enable the new virtual host configurations and required modules:
sudo a2ensite site1.conf
sudo a2ensite site2.conf
sudo a2enmod proxy
sudo a2enmod proxy_fcgi
Finally, reload, restart Apache:
sudo systemctl reload apache2 && sudo systemctl restart apache2