# Custom Apache Handler for Running Multiple PHP Versions Per VirtualHost

> How to run multiple PHP versions side-by-side in Apache VirtualHosts using PHP-FPM Unix sockets (Apache 2.4+) or CGI ScriptAlias handlers.

- Canonical URL: <https://carlossura.com/blog/custom-apache-handler-with-multiple-php-versions/>
- Author: Carlos Sura
- Published: 2021-05-14
- Updated: 2026-10-20
- Tags: apache, handlers, centos, linux, php, php-fpm

When migrating legacy PHP applications or consolidating multiple sites onto a single Linux server, you often need one Apache `VirtualHost` to run a specific PHP release (such as PHP 7.4 or PHP 8.3) while other VirtualHosts remain on the system default PHP version.

Below are both the modern **Apache 2.4 + PHP-FPM (`mod_proxy_fcgi`)** configuration and the fallback **CGI `ScriptAlias` / `Action` handler** for legacy Apache 2.2 servers.

---

## Modern Approach: Apache 2.4 with `mod_proxy_fcgi` and PHP-FPM Pools

On modern RHEL, Rocky Linux, AlmaLinux, Debian, and Ubuntu servers running **Apache 2.4+**, the cleanest and highest-performance method is running isolated `php-fpm` pools for each PHP version (for example via Remi's RPM repository on RHEL/Rocky or `ondrej/php` on Ubuntu) and routing `.php` requests over a Unix domain socket inside the `<VirtualHost>` block:

```apache
<VirtualHost *:443>
    ServerName app.example.com
    DocumentRoot /var/www/app/public

    <Directory /var/www/app/public>
        AllowOverride All
        Require all granted
    </Directory>

    # Route PHP scripts in this VirtualHost to the PHP 8.3 FPM socket
    <FilesMatch "\.php$">
        SetHandler "proxy:unix:/run/opt/remi/php83/php-fpm/www.sock|fcgi://localhost/"
    </FilesMatch>
</VirtualHost>
```

Using `mod_proxy_fcgi` with per-version Unix sockets gives you full opcode caching (`opcache`), process pool isolation, and zero CGI process-spawning overhead.

---

## Legacy Workaround: Apache 2.2 CGI `ScriptAlias` & `Action` Handler

When maintaining a legacy **CentOS 6 / Apache 2.2** environment where `mod_proxy_fcgi` is unavailable, you can bind a secondary `php-cgi` binary (such as PHP 7.4 compiled or installed side-by-side) directly to a single `<VirtualHost>` using `ScriptAlias` and `Action` right before the closing `</VirtualHost>` tag:

```apache
ScriptAlias /php74-cgi /opt/remi/php74/root/usr/bin/php-cgi
Action application/x-httpd-php74 /php74-cgi

<FilesMatch "\.php$">
    SetHandler application/x-httpd-php74
</FilesMatch>
```

---

## Security & Verification Checklist

**Ensure `cgi.force_redirect = 1`:** When using `php-cgi` with `ScriptAlias`, keep `cgi.force_redirect = 1` enabled in that PHP version's `php.ini` so visitors cannot invoke `/php74-cgi` directly via URL manipulation.
**Validate Apache Syntax Before Reloading:**

```bash
sudo apachectl configtest
sudo systemctl reload httpd
```
