Loading...
Real Time Concepts

Selective PHP-FPM Pools with Nginx

Selective PHP-FPM Pools

An advanced php-fpm use case is multiple pools for a single domain. One scenario where this could be useful is load balanced servers with lsyncd. Since file writes should only happen on the master server, a read-only pool is used to handle local requests and a read-write pool is used to direct requests to the master server.

Step 1 – Add Upstream Definitions

This approach requires 2 upstream definitions in the Nginx http block: one for the master (read-write) pool, and one for the local (read-only) pool. Note that the master pool must communicate with Nginx via a TCP socket and not a Unix socket, so that all servers can communicate with it.

Put this in the Nginx http block

# Local read-only socket
upstream ro_php_fpm { server unix:/var/run/php5-fpm.sock; }

# Master read-write socket
upstream rw_php_fpm { server master:9000; }

Step 2 – Add Map Definitions

Next, we have to define what kind of requests go to each pool. We’ll do this via the Nginx map module, which also goes in the http block. This is application-dependent; below are suitable configurations for Magento and WordPress.

Magento, put this in the Nginx http block

map “METHOD:$request_method COOKIE:<${cookie_adminhtml}> URL:$request_uri.” $fcgi_pass {
default ro_php_fpm;
~METHOD:POST rw_php_fpm;
~METHOD:PUT rw_php_fpm;
~URL:.*admin.* rw_php_fpm;
~URL:/var/export/ rw_php_fpm;
~URL:/install/ rw_php_fpm;
~URL:/contacts/ rw_php_fpm;
~URL:^media/captcha/.* rw_php_fpm;
~COOKIE:<> ro_php_fpm;
# ~COOKIE:<.+> rw_php_fpm; # Custom cookies can be added with regex
}

WordPress, put this in the Nginx http block

map “METHOD:$request_method URL:$request_uri.” $fcgi_pass {
default ro_php_fpm;
~URL:.*admin-ajax.* ro_php_fpm;
~METHOD:POST rw_php_fpm;
~METHOD:PUT rw_php_fpm;
~URL:.*admin.* rw_php_fpm;
}

Step 3 – Use the Map as PHP-FPM Proxy Target

To use these directives set the directive to in the block where you proxy to php-fpm within your block. fastcgi_pass $fcgi_pass location server

location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass $fcgi_pass;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}

Leave a Reply

Your email address will not be published. Required fields are marked *