Nginx – chrooting php-fpm with nginx

chrootnginxphp-fpm

I'm setting up a new server with PHP 5.3.9 and nginx, so I compiled PHP with the php-fpm SAPI options. By itself it works great using the following server entry in nginx:

server {
    listen 80;
    server_name domain.com www.domain.com;

    root /var/www/clients/domain.com/www/public;
    index index.php;

    log_format gzip '$remote_addr - $remote_user [$time_local] "$request" $status $bytes_sent "$http_referer" "$http_user_agent" "$gzip_ratio"';
    access_log /var/www/clients/domain.com/logs/www-access.log;
    error_log /var/www/clients/domain.com/logs/www-error.log error;

    location ~\.php$ {
            fastcgi_pass 127.0.0.1:9001;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /var/www/clients/domain.com/www/public$fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_script_name;
            include /etc/nginx/fastcgi_params;
    }
}

It servers my PHP files just fine. For added security I wanted to chroot my FPM instance, so I added the following lines to my conf file for this FPM instance:

# FPM config
chroot = /var/www/clients/domain.com

and changed the nginx config:

#nginx config for chroot
location ~\.php$ {
            fastcgi_pass 127.0.0.1:9001;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME www/public$fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_script_name;
            include /etc/nginx/fastcgi_params;
    }

With those changes, nginx gives me a File not found message for any PHP scripts. Looking in the error log I can see that it's prepending the root path to my DOCUMENT_ROOT variable that's passed to fastcgi, so I tried to override it in the location block like this:

fastcgi_param DOCUMENT_ROOT /www/public/;
fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;

but I still get the same error, and the debug log shows the full, unchrooted path being sent to PHP-FPM.

What am I missing to get this to work?

Best Answer

I have the same situation and this is my solition:

fpm config:

prefix = /var/www/example.com
chroot = $prefix
chdir = /
listen = tmp/php5-fpm.sock
slowlog = log/$pool.log.slow

nginx config:

 location ~ \.php$ {
    include /etc/nginx/fastcgi_params;
    fastcgi_pass unix:/var/www/example.com/tmp/php5-fpm.sock;
    fastcgi_param SCRIPT_FILENAME /htdocs$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_script_name;
    fastcgi_param DOCUMENT_ROOT /htdocs;
 }

folder structure of /var/www/example.com

drwxr-x---  6 www-data www-data 4096 May 22 10:57 .
drwxr-xr-x 10 root     root     4096 May 22 08:52 ..
drwxr-x---  2 www-data www-data 4096 May 22 10:57 htdocs
drwxr-x---  2 www-data www-data 4096 May 22 10:34 log
drwxr-x---  2 www-data www-data 4096 May 22 10:56 tmp