To install and configure PHP-FPM (FastCGI Process Manager) with Apache2, you’ll need to add the php-fpm package and configure Apache2 to use it with the proxy_fcgi module. PHP-FPM offers better performance, scalability, and resource management compared to the standard mod_php method (libapache2-mod-php), especially for handling high loads.
Here’s how to install and configure PHP-FPM with Apache2:
To install PHP-FPM and the necessary PHP packages, run the following commands:
sudo apt update
sudo apt install php-fpm
You need to enable two Apache modules for PHP-FPM to work: proxy_fcgi and setenvif. These modules allow Apache to pass PHP requests to PHP-FPM.
Run the following commands to enable the modules:
sudo a2enmod proxy_fcgi setenvif
After enabling the modules, restart Apache:
sudo systemctl restart apache2
To configure Apache to use PHP-FPM, you need to modify the virtual host configuration. If you’re using the default virtual host, edit the following file:
sudo nano /etc/apache2/sites-available/000-default.conf
Find the DocumentRoot line and just below it, add the following configuration to tell Apache to use PHP-FPM for .php files:
<FilesMatch \.php$>
SetHandler "proxy:unix:/run/php/php-fpm.sock|fcgi://localhost/"
</FilesMatch>
Make sure to adjust the path /run/php/php-fpm.sock based on the PHP version installed on your system. For example, if you’re using PHP 8.1, it might be:
SetHandler "proxy:unix:/run/php/php8.1-fpm.sock|fcgi://localhost/"
After making changes to the Apache virtual host configuration, restart both Apache and PHP-FPM:
sudo systemctl restart apache2
sudo systemctl restart php8.1-fpm # Replace with your PHP version
As with the previous setup (mod_php), you can create a PHP test file to ensure everything is working. Create a file named info.php in your web root directory:
sudo nano /var/www/html/info.php
Add the following content to the file:
<?php
phpinfo();
?>
Save and exit. Now, open your browser and navigate to:
http://your-server-ip/info.php
If everything is configured correctly, you should see the PHP info page, which will show that PHP is now being handled by PHP-FPM.
As before, you might need additional PHP modules for your applications. You can install them using:
sudo apt install php-mysql php-gd php-xml
After installing additional PHP modules, restart PHP-FPM and Apache:
sudo systemctl restart php8.1-fpm
sudo systemctl restart apache2
Once you’ve confirmed that PHP-FPM is working, it’s a good idea to delete the info.php file for security reasons:
sudo rm /var/www/html/info.php
You’ve now configured Apache2 to work with PHP-FPM instead of mod_php. This setup is more efficient, especially for high-traffic websites or complex applications, as PHP-FPM can handle multiple processes and provides better resource management.