Setup Nginx with php 7 on Ubuntu 16.04

Here’s a quick guide to setting up the http server Nginx with the latest version of php.
 

Install Nginx

Update repositories

sudo apt-get update

Install Nginx

sudo apt-get install nginx

Check Nginx is running

systemctl status nginx

If all has went to plan, the following will be output

Active: active (running) since Thu 2016-07-07 16:27:22 IST; 2h 19min ago

Press ctrl + c to return to a shell prompt

If you visit your server’s IP address in a web browser you should be greeted with the Nginx welcome page.

 

Install php 7.0

If you’re installing php, you’ll almost certainly want to install the php-mysql module, too

sudo apt-get install php-fpm php-mysql

Make a small change that will tighten security a lot

sudo nano /etc/php/7.0/fpm/php.ini

Find the following line

; cgi.fix_pathinfo=1

Change it to

cgi.fix_pathinfo=0

This will prevent php from executing any script except the exact script that was requested

Restart php

sudo systemctl restart php7.0-fpm

An example Nginx config using php

Open the default Nginx config file

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

Change it to the following

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;
    index index.php index.html index.htm;

    server_name server_domain_or_IP;

    location / {
        try_files $uri $uri/ =404;
    }

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

    location ~ /\.ht {
        deny all;
    }
}

Reload Nginx to have changes take effect

sudo systemctl reload nginx

Test the php configuration

Create a phpinfo file

sudo nano /var/www/html/phpinfo.php

Add the following code

<?php phpinfo(); ?>

Visit http://YOUR_SERVER_IP/phpinfo.php in a web browser and you should see the php info file.

Be sure to remove the phpinfo.php file when done!

sudo rm /var/www/html/phpinfo.php

Leave a Reply

Your email address will not be published. Required fields are marked *