Nginx – How to i use two different php-fpm pools depending on url

nginxPHPphp-fpm

I would also like to use 2 php-fpm pools.

My directory structure looks like this:

/home/test/index.php
/home/test/contact.php
/home/test/stats.php

document root is:

root /home/test;

When I call the stats.php the pool with the fastcgi_pass 127.0.0.1:9001; should be taken, but all other PHP's (index.php, contatct.php) should use the pool with the fastcgi_pass 127.0.0.1:9000; should be taken.

If I insert this location block every PHP uses the fastcgi_pass 127.0.0.1:9001

location = /stats.php {
       include fastcgi_params;
       fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 
       fastcgi_pass 127.0.0.1:9001;
}

No matter if I insert it before or after this block

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    include /etc/nginx/fastcgi_params;
    fastcgi_pass 127.0.0.1:9000;
}

Thanks

Update 12.06.2020:

i have the following in the /etc/nginx/nginx.conf:

map $request_uri $pool {
    "/stats.php" 127.0.0.1:9001;
    default 127.0.0.1:9000;
}

and in the /etc/nginx/sites-enabled/default:

location \.php$ {
    try_files $uri =404;
    include /etc/nginx/fastcgi_params;
    fastcgi_pass $pool;     
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

nevertheless all PHP's only use the fastcgi_pass 127.0.0.1:9000

The tip with the map function comes from here:
Nginx: How to use a different php-fpm pool depending on url

How must the map function looks like when i want to use stats.php with params? e.g.

stats.php?time=123456&id=1754852

It looks like it doesn't work like this

map $request_uri$is_args$args $pool {
    "/stats.php" 127.0.0.1:9001;
    default 127.0.0.1:9000;
}

Best Answer

A location with a regex needs "~" or "~*", as in

location ~ \.php$ {
  fastcgi_pass $pool;
}

For the map request to work when there are request parameters, one should use the $uri iso. the $request_uri.

map $uri $pool {
  "/stats.php" 127.0.0.1:9001;
  default 127.0.0.1:9000;
}

Alternative would be to use $request_uri and a regex iso. "/stats.php".