What is the easiest way to enable PHP on nginx?

The following method will get you started fast on Ubuntu 12.04:

Install the dependences:

sudo apt-get install php5-common php5-cli php5-fpm

Install nginx:

sudo apt-get install nginx

Start nginx:

sudo service nginx start

Test that it's working (should see "Welcome to nginx!")

sudo service nginx stop

In your nginx site configuration (/etc/nginx/sites-available/default), modify the line in the server {} section

index index.html index.htm to index index.php index.html index.htm.

Uncomment the lines in the server {} section starting with

listen for ipv4 / ipv6 both.

Scroll down to where it says location ~ \.php { and uncomment lines so it looks like this:

location ~ \.php$ {
  fastcgi_split_path_info ^(.+\.php)(/.+)$;
  fastcgi_pass 127.0.0.1:9000;
  fastcgi_index index.php;
  include fastcgi_params;
}

sudo service php5-fpm restart sudo service nginx restart

Your default web root is located at /usr/share/nginx/www (per the config file). (See root /usr/share/nginx/www;

(Note: For Ubuntu 12.10 or newer, you will need to replace the fastcgi_pass 127.0.0.1:9000; line with this to make it work: fastcgi_pass unix:/var/run/php5-fpm.sock;)


EDIT: As pointed out by Matt Browne you may be interested by this more recent post:
How To Install Linux, Nginx, MySQL, PHP (LEMP stack) in Ubuntu 16.04


The papashou's answer is correct on old Ubuntu 12.04. Since Ubuntu 12.10, the configuration is a bit different. Here is what I did:

Install

sudo apt-get install nginx php5-fpm

Enable PHP

Uncomment the following lines in configuration file /etc/nginx/sites-available/default

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

#   # With php5-cgi alone:
#   fastcgi_pass 127.0.0.1:9000;
    # With php5-fpm:
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
}

Start (or restart)

sudo service php5-fpm restart
sudo service nginx restart

Test nginx

Opening this link http://localhost should display "Welcome to nginx!"

Test php

Create a php file:

  • The target path is the output of

    awk -F' |;' '/^[^#]*root/ {print $2}' /etc/nginx/sites-available/default
    

    e.g. /usr/share/nginx/www

  • Write a info.php file with:

    echo '<?php phpinfo(); ?>' | \
        sudo tee /usr/share/nginx/www/info.php
    

    or as one-liner

    echo '<?php phpinfo(); ?>' | \
        sudo tee "$(awk -F' |;' '/^[^#]*root/ {print $2}' /etc/nginx/sites-available/default)/info.php"
    

Opening http://localhost/info.php should display the PHP information page.

Tags:

Nginx

Php