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
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
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
- How To Install Linux, Nginx, MySQL, PHP (LEMP stack) in Ubuntu 16.04
- Stack Overflow - Rewrite all requests to index.php with nginx
- PHP-FPM - A simple and robust FastCGI Process Manager for PHP
First published: 16th August 2018