Skip to content

Running Nginx with PHP via FastCGI

Build a default Nginx install; I used the following configure arguments, but these are not necessary for using PHP/FastCGI (only for my environment):

./configure --prefix=/opt/nginx-0.6.34 --user=apache --group=apache

Build PHP for FastCGI, with the following configure arguments:

./configure  --prefix=/opt/php-5.2.8 --enable-fastcgi --enable-force-cgi-redirect --with-gd --with-mysqli --enable-mbstring

--enable-fastcgi --enable-force-cgi-redirect are the important arguments to configure; the others are simply needed for my environment.

Use the following script to start the PHP FastCGI processes, adapted from Nginx With PHP As FastCGI Howto:

#!/bin/bash

## ABSOLUTE path to the PHP binary
PHPFCGI="/opt/php/bin/php-cgi"

## tcp-port to bind on
FCGIPORT="8888"

## IP to bind on
FCGIADDR="127.0.0.1"

## IP address to accept connections from:
FCGI_WEB_SERVER_ADDRS=127.0.0.1

## number of PHP children to spawn
PHP_FCGI_CHILDREN=4

## number of request before php-process will be restarted
PHP_FCGI_MAX_REQUESTS=1000

# allowed environment variables sperated by spaces
ALLOWED_ENV="PATH USER"

## if this script is run as root switch to the following user
USERID=apache

################## no config below this line

if test x$PHP_FCGI_CHILDREN = x; then
  PHP_FCGI_CHILDREN=5
fi

ALLOWED_ENV="$ALLOWED_ENV PHP_FCGI_CHILDREN"
ALLOWED_ENV="$ALLOWED_ENV PHP_FCGI_MAX_REQUESTS"
ALLOWED_ENV="$ALLOWED_ENV FCGI_WEB_SERVER_ADDRS"

if test x$UID = x0; then
  EX="/bin/su -m -c \"$PHPFCGI -q -b $FCGIADDR:$FCGIPORT\" $USERID"
else
  EX="$PHPFCGI -b $FCGIADDR:$FCGIPORT"
fi

echo $EX

# copy the allowed environment variables
E=

for i in $ALLOWED_ENV; do
  E="$E $i=${!i}"
done

# clean environment and set up a new one
nohup env - $E sh -c "$EX" &> /dev/null &

I found it necessary to add the FCGI_WEB_SERVER_ADDRS variable to avoid errors similar to the following from the PHP processes (visible by not redirecting output to /dev/null in the last line of the script):

Connection from disallowed IP address '127.0.0.1' is dropped.

The nginx.conf file is modified as follows (for a /var/www/html webroot):

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
            root           /var/www/html;
            fastcgi_pass   127.0.0.1:8888;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /var/www/html$fastcgi_script_name;
            include        fastcgi_params;
        }

Additional references: Nginx English Wiki

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*