Nginx – Add PHP-FPM

Recently I posted an entry related to the installation and basic configuration of the Nginx web server. In this episode, we’ll take care of adding PHP to it. Unlike Apache, we can not use the module for the server (mod_php) because Nginx does not have its native support. However, it is possible to redirect PHP-related requests to a separate PHP wrapper service. For this purpose, we will re-use Ubuntu distribution as well as an additional PPA repository. The entry does not describe the exact configuration of PHP, but only its installation and connection with Nginx – details of additional settings will be raised in the subsequent episodes of the cycle.

Nginx installation and first configuration

Nginx virtual host configuration

Use PHP-FPM with Nginx

Describe and change php.ini settings

PHP-FPM – config improvements

Use strong Nginx encryption settings

Nginx optimizations, tips and tricks (work in progress)

Adding respository and PHP-FPM installation

The first task is to add the appropriate repository with PHP packages. We find them in the original Ubuntu repository, but not in the newest versions. Additional Ondrej Sury PPA provides access to more PHP extensions as well as newer versions such as PHP 7.1 and PHP 7.2. Since PHP 7.0, it is possible to install several different versions of PHP and use them interchangeably – all depend on the configuration of a specific website. The repository can be added with the following command:

Next step, installation of required PHP packages. Here is list that I can recommend for many cases:

And there is some optional packages:

php7.1-sqlite3 (for sqlite)
php7.1-intl (for languages, currents, times etc.)
php-imagick (for images processing)
php-mongodb (for mongodb databases)
php-pear (for pear packages)
php-xdebug – for debugging

Adding new user for website and PHP-FPM wrapper

We want to move all website files inside user directory and also run PHP-FPM wrapper as this user. We need to create new account for website:

And create website directory:

Put example phpinfo code into index.php file:

Create spawner configuration

Next step is to create spawner configuration for this test user. We need to create/edit file /etc/php/7.1/fpm/pool.d/test.conf. We will use simple ondemand spawner mode, which I described on previous blog entry. Here is simple, full configuration of this file:

Add PHP-FPM to Nginx virtual host

Last step is to add our PHP-FPM wrapper to Nginx virtual host file. We should just add location block inside server {} block:

After that, just restart PHP-FPM to create new spawner for this user and also Nginx to reload configuration – PHP should work.