October 21, 2018

PHP, FPM, and Nginx

We'll install PHP and configure Nginx to send requests to PHP files off to PHP-FPM

PHP

We can see we have php 7.0 available out of the box:

sudo apt-cache show php-cli

Instead of using that, we'll start by installing the latest PHP 7.1, via the populate PHP repository.

# Add repository and update local cache of available packages
sudo add-apt-repository -y ppa:ondrej/php
sudo apt-get update

# Search for packages starting with PHP, 
# we'll see php7.1-* packages available
sudo apt-cache search -n php*

# Install PHP-FPM, PHP-CLI and modules
sudo apt-get install -y php7.1-fpm php7.1-cli php7.1-curl php7.1-mysql php7.1-sqlite3 \
    php7.1-gd php7.1-xml php7.1-mcrypt php7.1-mbstring php7.1-iconv

Once that's installed, we can see some similar conventions from Nginx (and other software in Debian/Ubuntu).

SAPI

PHP on Debian/Ubuntu is divided by version and Server Application Programming Interface. A SAPI is the context in which PHP is run. The most common are:

  • cli - when running on the command line
  • fpm - when fulfilling a web request via fastcgi
  • apache2 - when run in Apache's mod-php

Configuration

We can see the configuration split between version and SAPI by checking the file paths within /etc:

cd /etc/php
ls -lah

> ... 5.6/
> ... 7.0/
> ... 7.1/

cd 7.1
ls -lah

> ... cli/
> ... fpm/

Within each SAPI directory (e.g. cli or fpm), there is a php.ini file and a conf.d directory. We can edit php.ini per SAPI and use symlinks within the conf.d directory to enable or disable modules per SAPI.

Modules

PHP on Debian/Ubuntu use Symlinks to decide which ones are loaded per SAPI. All module configuration files are located in /etc/php/<version>/mods-available, and then loaded in via symlinks at /etc/php/<version>/<sapi>/conf.d.

Nginx

Once PHP is installed, we can configure Nginx to send PHP requests off to PHP-FPM:

server {
    listen 80;

    root /var/www/html;

    server_name _;

    index index.html index.htm index.debian-default.html index.php;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

    location ~ \.php$ {
        incude snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.1-fpm.sock;
    }
}

Once edits are complete we can test Nginx and reload:

sudo nginx -t
sudo service nginx reload

In the video, I show you some behavior around the above configuration. Most notably, the try_files configuration allows for "pretty URLs", meaning we don't need to add index.php into the URL within our browser for Nginx to use the index.php file.

The above configuration file will search for php files within the /var/www/html directory and send requests to PHP-FPM if a file is requested that ends in the .php extension.

All Topics