How to change PHP version in Apache2 (Prefork MPM)

Apache2 default page
Apache2 default page

Introduction

The Apache HTTP Server powers over 30% of websites worldwide. Its default configuration is typically sufficient for standard workloads. 
Apache is often paired with PHP, where configuration and optimization play a critical role in overall application performance.

This tutorial demonstrates how to change PHP version on Apache2 web server with Prefork MPM. The Prefork MPM Apache2 is a non-threaded, pre-forking module included with Apache HTTP Server, designed for maximum compatibility and stability. In this setup, Apache directly executes PHP scripts through mod_php.

 

Prerequisites

In order to be able to use this tutorial, you will need to have Apache web server installed with required PHP modules.

Works on Ubuntu 16.04, 18.04, 20.04, 22.04
Applications: Apache, PHP(8.0,8.1, any PHP version)
 

Install Apach2 PHP 8.1 module,
sudo apt-get install libapache2-mod-php8.1

Install new required Apach2 PHP 8.1 module,

This package provides the PHP module for the Apache 2 webserver.  
Please note that this package ONLY works with Apache's prefork MPM, as it is not compiled thread-safe.

Disabling and enabling the desired PHP version
sudo a2dismod php8.0
sudo a2enmod php8.1
sudo service apache2 restart

Disabling the current php8.0 module PHP 8.0, enabling the desired PHP 8.1 version php8.1, and restarting the Apache2.
PHP versions can be any (Installed previously)

Summary

This guide explains how to switch between different PHP versions in Apache2 when using the Prefork MPM. It covers disabling the current mod_php module, enabling the desired PHP version, and restarting Apache to apply the changes.