This is a continuation of the article: Nginx with php@FastCGI support part I
Before starting the nginx configuration, we need to get the following packages: php5, php5-cgi, spawn-cgi; if we want to use a database, e.g. mysql, additionally: php5-mysql, php5-mcrypt. We'll borrow the spawn-cgi application from the lighttpd package.
- first we configure php5-cgi, editing the file /etc/php5/cgi/php.ini
- and set in it: cgi.fix_pathinfo=1
- we download the lighttpd package: wget http://download.lighttpd.net/lighttpd/releases-1.4.x/lighttpd-1.4.26.tar.gz
- we unpack it: tar -xvjf lighttpd-1.4.26.tar.gz , and go into the directory
- ./configure
- we compile with make
- and take what interests us: cp src/spawn-fcgi /usr/bin/spawn-fcgi
- nano /usr/bin/php-fastcgi and paste in:
#!/bin/sh /usr/bin/spawn-fcgi -a 127.0.0.1 -p 9000 -C 3 -u www-data -f /usr/bin/php5-cgi
where:
-a - the interface it listens on
-p - the port it listens on
-C - the number of processes started
-u - with what permissions we run the process
- next we create a startup script for fastcgi, creating the file /etc/init.d/fastcgi
#!/bin/bash
PHP_SCRIPT=/usr/bin/php-fastcgi
RETVAL=0
case "$1" in
start)
$PHP_SCRIPT
RETVAL=$?
;;
stop)
killall -9 php5-cgi
RETVAL=$?
;;
restart)
killall -9 php5-cgi
$PHP_SCRIPT
RETVAL=$?
;;
*)
echo "Usage: php-fastcgi {start|stop|restart}"
exit 1
;;
esac
exit $RETVAL
- Now let's move on to configuring nginx itself Put simply, the difference between a configuration serving static content and one serving dynamic pages lies in the location directive:
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME our_site_directory$fastcgi_script_name;
include fastcgi_params;
}
}
It's worth optimizing the configuration so that only requests requiring "dynamic page" serving reach the PHP interpreter.
PHP can also serve static files or images, but nginx will do it faster and at lower cost.
For example:
location = /images {
auth_basic off;
root /var/www/site/images;
}
location / {
root /var/www/site;
index index.php;
}
location = /50x.html {
root /var/www/nginx-default;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /var/www/site$fastcgi_script_name;
include fastcgi_params;
}
}