We will see how to let nginx execute PHP scripts and display their results instead of their content.
Configuration of PHP-FPM
Several possibility are available to execute PHP scripts Apache module, CGI, FastCGI and FPM. The later is an adaptation of the FastCGI version for heavy-loaded sites. It is the recommended installation to use with nginx.
We will start by installing the FPM version of PHP5
# apt install php5-fpm
nginx can discuss with the PHP-FPM process either through TCP socket or Unix socket. Since we will suppose nginx and PHP-FPM are on the same machine, we will use the Unix socket version.
First we check the configuration in the PHP-FPM configuration file
(php5/fpm/pool.d/www.conf
):
38 listen = /var/run/php5-fpm.sock
Then we restart the PHP-FPM service
# service php5-fpm restart
Configuration of nginx
We say to nginx where to find the PHP socket and to pass it the PHP files
(extension .php
). We need to put the following lines in the vhost files
needing it. For the ease of the host configuration just put that lines in a new
file called /etc/nginx/php.conf
.
# pass the PHP scripts to PHP-FPM server listening on :code:`/var/run/php5-fpm.sock;`
location ~ \.php$ {
include snippets/fastcgi-php.conf;
# With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
}
You will just need to include that file in the virtual host that need to execute
php scripts. For example for the default site
(/etc/nginx/sites-available/default
):
1 server {
2 listen 80 default_server;
3 listen [::]:80 default_server;
4
5 root /var/www/html;
6
7 # Add index.php to the list if you are using PHP
8 index index.html index.htm index.php;
9
10 server_name _;
11
12 location / {
13 # First attempt to serve request as file, then
14 # as directory, then fall back to displaying a 404.
15 try_files $uri $uri/ =404;
16 }
17 include php.conf;
18 }
A restart of nginx is then necessary to take the new configuration into account:
# service nginx restart