Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Ubuntu 16.04 - Install NGINX with PHP

This tutorial will quickly get you started with deploying an NGINX webserver and configuring it to work with using PHP 7.0. If you want to install MySQL, MariaDB, or PostgreSQL as well, that's easy enough to do separately after/before completing this tutorial.

Steps

Install NGINX and php-fpm

sudo apt update
sudo apt install nginx php-fpm -y

PHP-FPM stands for "FastCGI Process Manager" is an alternative PHP FastCGI implementation.

Now lets increase security by configuring php-fpm to only execute exact matches for files, rather than executing the closest matching file.

SEARCH=";cgi.fix_pathinfo=.*"
REPLACE="cgi.fix_pathinfo=1"
FILEPATH="/etc/php/7.0/fpm/php.ini"
sudo sed -i "s|$SEARCH|$REPLACE|" $FILEPATH

Restart the fast-cgi processor for the changes to take effect

sudo systemctl restart php7.0-fpm

Configure nginx to use the php fast cgi processor.

sudo editor /etc/nginx/sites-available/default

Replace it with the following contents.

HOSTNAME="10.1.0.113"

sudo echo "server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;
    index index.php index.html index.htm index.nginx-debian.html;

    server_name $HOSTNAME;

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

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

    location ~ /\.ht {
        deny all;
    }
}" | sudo tee  /etc/nginx/sites-available/default

Test the changes with:

sudo nginx -t

You should get the following output:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Reload nginx to use the changes with:

sudo nginx -s reload

By using reload instead of runing a service nginx restart command, we gracefully handle any existing http requests with no downtime of the webserver.

Finally, lets create a basic site that will output everything about our php configuration

sudo rm /var/www/index/html/*

sudo echo "<?php
phpinfo();" | sudo tee /var/www/html/index.php

Now navigate to your server's hostname or IP and you will see the following:

References

Last updated: 5th June 2024
First published: 16th August 2018