I need to run a LNMP (Linux Nginx Mysql PHP) stack for development. Here’s an easy way how you can run PHP5 through FastCGI on Nginx as well.

Install required packages

You need to install these packages: php5-common, php5-cgi and nginx: sudo apt-get update sudo apt-get install php5-common php5-cgi nginx

Start/stop PHP-FastCGI

Create a start script in your /etc/init.d directory:

sudo gedit /etc/init.d/php-fastcgi

And add this code in it:

#!/bin/bash
BIND=127.0.0.1:9000
USER=www-data
PHP_FCGI_CHILDREN=15
PHP_FCGI_MAX_REQUESTS=1000

PHP_CGI=/usr/bin/php-cgi
PHP_CGI_NAME=`basename $PHP_CGI`
PHP_CGI_ARGS="- USER=$USER PATH=/usr/bin PHP_FCGI_CHILDREN=$PHP_FCGI_CHILDREN PHP_FCGI_MAX_REQUESTS=$PHP_FCGI_MAX_REQUESTS $PHP_CGI -b $BIND"
RETVAL=0

start() {
    echo -n "Starting PHP FastCGI: "
    start-stop-daemon --quiet --start --background --chuid "$USER" --exec /usr/bin/env -- $PHP_CGI_ARGS
    RETVAL=$?
    echo "$PHP_CGI_NAME."
}
stop() {
    echo -n "Stopping PHP FastCGI: "
    killall -q -w -u $USER $PHP_FASTCGI
    RETVAL=$?
    echo "$PHP_CGI_NAME."
}

case "$1" in
        start)
            start
    ;;
        stop)
            stop
    ;;
        restart)
            stop
            start
    ;;
        *)
            echo "Usage: php-fastcgi {start|stop|restart}"
            exit 1
    ;;
esac
exit $RETVAL

Make it executable:

sudo chmod +x /etc/init.d/php-fastcgi

Make it launch at startup (optional):

sudo update-rc.d php-fastcgi defaults

Launch it manually:

sudo /etc/init.d/php-fastcgi start

That’s it, now you should be able to use PHP on Nginx through PHP-FastCGI

Nginx configuration example

Example server config:

location ~ \.php$ {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /var/www/$fastcgi_script_name;
    include fastcgi_params;
}

Restart NginX:

sudo /etc/init.d/nginx restart

Set up a phpinfo() sample page:

echo "<?php phpinfo();" > /var/www/index.php

Visit the page as you normally would. You should see a PHP information page.