Nginx and PHP-FPM: two applications and the right worker

Connect Nginx to two FPM pools through Unix sockets and check HTTP, process identities and access denials in a separate test environment.

An arch and two separate paths leading to different pavilions.

In the preceding exercise PHP-FPM answered direct FastCGI requests through Unix sockets. We have now connected it to Nginx: an HTTP request must pass through the web server and run in the worker belonging to the application the client requested.

This manual exercise used a separate disposable Debian 13 VM with PHP 8.5.12. It contains two test applications, frontend and admin; it is not a deployment of the journal to its working server. The listener is limited to 127.0.0.1:8080. DNS, TLS and external ingress are outside this step.

Two roots and two identities

The frontend root is /srv/php-fpm-demo/products/shop/frontend; admin uses the neighbouring /srv/php-fpm-demo/products/shop/admin. Nginx sees each application’s public directory. A dummy private.txt sits one level above it, while mutable cache and log directories belong under its own var. Root owns the code. Separate unprivileged nonlogin users, proof-web and proof-admin, work only with their own mutable directories.

A separate Unix socket connects each root to the appropriate FPM pool. This is an excerpt of the frontend pool; admin has its own user and proof-admin.sock.

[proof-web]
user = proof-web
group = proof-web
listen = /run/deploy-cli-php85/proof-web.sock
listen.owner = root
listen.group = www-data
listen.mode = 0660
pm = static
pm.max_children = 1
clear_env = yes
security.limit_extensions = .php

The socket belongs to root:www-data with mode 0660. An Nginx worker running as www-data can forward a request; the PHP runtime user does not gain permission to connect directly to that socket. This excerpt does not replace the full configuration: the fixture also defines private temporary directories, a custom systemd service and filesystem restrictions.

Only the specified front controller reaches PHP

We did not add a general rule for every URL containing .php. This fixture has one dynamic entry point: public/index.php. The root URL is rewritten to it, health.txt has a separate static route, and other URLs are rejected. This is a shortened excerpt of the actual frontend server block:

server {
    listen 127.0.0.1:8080;
    server_name frontend.example.test;
    root /srv/php-fpm-demo/products/shop/frontend/public;
    location = /health.txt { try_files $uri =404; }
    location = / { rewrite ^ /index.php last; }
    location = /index.php {
        fastcgi_pass unix:/run/deploy-cli-php85/proof-web.sock;
        fastcgi_param SCRIPT_FILENAME /srv/php-fpm-demo/products/shop/frontend/public/index.php;
        fastcgi_param SCRIPT_NAME /index.php;
        fastcgi_param REQUEST_METHOD $request_method;
        fastcgi_param QUERY_STRING $query_string;
        fastcgi_param REQUEST_URI $request_uri;
        fastcgi_param HTTP_PROXY "";
    }
    location / { return 404; }
}

SCRIPT_FILENAME is a literal value: a client cannot choose a PHP file through the URL. This is deliberately a narrow test route. The full configuration also passes Content-Type, Content-Length, protocol, server name/port, remote address and REDIRECT_STATUS. Admin repeats the same structure with its own host, public directory and socket. A separate default_server on the same local port returns 404 for an unknown Host.

Exact locations are described in the Nginx location documentation; parameters and Unix sockets are covered by the FastCGI module documentation. A real application needs routes defined by its own contract. This narrow example is not a complete routing rule for every Symfony URL.

Installation and startup are separate steps

Before installing packages we prepared a shared startup guard. It covered Nginx, the packaged PHP-FPM service, and the session cleanup service and timer. It returned 101 for a protected invocation and 0 for an unrelated control. After both roles were installed, the packaged services remained masked/inactive and the policy was unchanged.

After writing the configuration we checked Nginx and FPM syntax separately. Our Nginx drop-in set Requires and After for deploy-cli-php85.service. We then explicitly started the services: custom FPM and Nginx became active/running, while startup remained disabled. The packaged php8.5-fpm.service stayed masked. This tests the current start, not automatic startup after a reboot.

The HTTP response must identify the right worker

Requests to the same local port are distinguished by their Host header:

curl --header 'Host: frontend.example.test' http://127.0.0.1:8080/
curl --header 'Host: admin.example.test' http://127.0.0.1:8080/
curl --header 'Host: frontend.example.test' http://127.0.0.1:8080/health.txt

Both dynamic responses returned status 200. The diagnostic index.php reported the pool name, PHP 8.5.12, the fpm-fcgi SAPI, PID and effective UID/GID. These were matched to the actual proof-web and proof-admin users in this VM. Numeric UIDs are not portable constants. Static health.txt also returned 200 with the exact text belonging to its application.

Reduced live recheck of the manual fixture: two pools respond through Nginx and unrelated paths are denied.

Denial checks complement a successful request

For both hosts, /.env, /private.txt, /var/cache/, /other.php, /index.php/extra and /health.txt/extra returned 404. Requests for /../private.txt and /%2e%2e/private.txt received 400: Nginx rejected traversal before routing. An unknown Host received 404.

These traversal requests used Python http.client, passing the request target literally without normalizing /../ first. This is the exact call structure; admin.example.test was checked in the same way:

import http.client

for target in ("/../private.txt", "/%2e%2e/private.txt"):
    connection = http.client.HTTPConnection("127.0.0.1", 8080)
    connection.request("GET", target, headers={"Host": "frontend.example.test"})
    response = connection.getresponse()
    print(target, response.status)
    response.read()
    connection.close()

To reproduce this with curl, use --path-as-is: otherwise the client removes /../ before sending it. This is client behaviour, not an Nginx response. The option is documented in curl --path-as-is.

Separately, PHP in each pool read its own dummy private.txt and saw its own cache as writable. The other pool’s private/cache paths and changes to its own code were unavailable. Direct connections by both runtime users to either FastCGI socket were denied. A correct 200 response therefore did not hide mixed identities or access to the neighbouring application.

This step connected two local HTTP entry points to two FPM pools on one manual fixture. It does not add external access or replace testing a real application under load. The separate CLI run and its results follow below.

Repeating the setup through CLI with one package history

On a separate clean Debian VM, the CLI installed Nginx, PHP and three data services. Final Nginx configuration/activation uses the original approved plans and the full history of nine package transitions. The old dpkg state is not replaced with the new one: each node and its dependencies are checked, while the required PHP runtime is read against its own original activation manifest.

We ran this separate history check. PRIVATE_DIR is an absolute path to the operator’s private files, and PHP_KEY_SHA256 is the SHA256 of the public repository key. References contains the original plans, manifests and nine node pins; the output file must be new.

The CLI then separately planned and applied Nginx configuration and activation. A subsequent activation-verify over a new SSH connection checked the runtime and real local HTTP requests to both applications. This completes startup in the current boot; enabling and rebooting the whole CLI stack remains a separate next step.

The CLI checks the fixed local /__deploy_cli_php_runtime endpoint. It sends a fixed read-only worker-probe.php outside public to the selected pool; the URI cannot select an arbitrary file. Those responses establish the connection to both PHP workers. The future Article application has not yet been delivered to this fixture.

deploy-cli host runtime-history inspect \
  --env-file "$PRIVATE_DIR/administrator.env" \
  --request-file "$PRIVATE_DIR/request.json" \
  --fpm-file "$PRIVATE_DIR/php-profile.json" \
  --key-file "$PRIVATE_DIR/php-repository.gpg" \
  --key-sha256 "$PHP_KEY_SHA256" \
  --references-file "$PRIVATE_DIR/history-references.json" \
  --output-file "$PRIVATE_DIR/history-proof-new.json"
curl --header 'Host: frontend.example.test' http://127.0.0.1:8080/__deploy_cli_php_runtime
curl --header 'Host: admin.example.test' http://127.0.0.1:8080/__deploy_cli_php_runtime

This is a reduced summary of the actual committed runtime journal. It shows two successful responses and the same denial controls for each host; an individual HTTP response uses a different JSON shape.

{
  "phase": "committed",
  "http_checks": 20,
  "pools": [
    {
      "host": "admin.example.test",
      "status": 200,
      "php_branch": "8.5",
      "sapi": "fpm-fcgi",
      "extensions": 39,
      "opcache_running": true
    },
    {
      "host": "frontend.example.test",
      "status": 200,
      "php_branch": "8.5",
      "sapi": "fpm-fcgi",
      "extensions": 39,
      "opcache_running": true
    }
  ],
  "denials_for_each_host": [
    {
      "method": "POST",
      "uri": "/__deploy_cli_php_runtime",
      "status": 403
    },
    {
      "method": "GET",
      "uri": "/__deploy_cli_php_runtime?unexpected=1",
      "status": 404
    },
    {
      "method": "GET",
      "uri": "/worker-probe.php",
      "status": 404
    },
    {
      "method": "GET",
      "uri": "/index.php/path-info",
      "status": 404
    },
    {
      "method": "GET",
      "uri": "/.env",
      "status": 404
    },
    {
      "method": "GET",
      "uri": "/../private.txt",
      "status": 400
    }
  ],
  "unknown_host_status": 404
}

A separate CLI successor for Nginx startup

After rebooting the retained CLI fixture, Nginx was inactive and disabled, while PHP had independently verified startup in the new boot. The new startup step does not replay configuration or activation. It checks their original plans and journals, signed archives, the vendor unit, every stock configuration file and the actual readiness of both PHP pools.

The original 40-deploy-cli-origin.conf remains in nginx.service.d, retaining the owned origin commands and firewall dependency. The new 80-deploy-cli-runtime-startup.conf adds only the PHP-FPM dependency:

[Unit]
Requires=deploy-cli-php85.service
After=deploy-cli-php85.service

Both dependencies are checked in systemd. Immediately before start, the CLI rechecks stopped/disabled Nginx, exact configuration and live PHP. Seven separate journalled steps write the drop-in, reload units, start the service, verify HTTP, create the exact enable link, reload units again and verify the enabled runtime. Successful apply includes independent reads over a new SSH connection.

PRIVATE_DIR is an absolute private directory. nginx-startup-inputs.json contains schema_version: 1 and the original php and nginx references: PHP activation_file, startup_request_file and startup plan/SHA/manifest; Nginx profile_file, dependencies_file, configuration and activation plan/SHA/manifest. The original PHP startup request retains its startup boot; current-console-request independently confirms the current boot.

NGINX_STARTUP_ARGS=(
  --env-file "$PRIVATE_DIR/administrator.env"
  --request-file "$PRIVATE_DIR/install-request.json"
  --fpm-file "$PRIVATE_DIR/php-profile.json"
  --key-file "$PRIVATE_DIR/php-archive-keyring.gpg"
  --key-sha256 "$PHP_PUBLIC_KEY_SHA256"
  --references-file "$PRIVATE_DIR/history-references.json"
  --current-request-file "$PRIVATE_DIR/current-console-request.json"
  --firewall-pin-file "$PRIVATE_DIR/firewall-pin.json"
  --startup-inputs-file "$PRIVATE_DIR/nginx-startup-inputs.json"
  --plan-file "$PRIVATE_DIR/nginx-startup-plan.json"
)

deploy-cli host runtime-startup nginx plan "${NGINX_STARTUP_ARGS[@]}"

deploy-cli host runtime-startup nginx apply "${NGINX_STARTUP_ARGS[@]}" \
  --plan-sha256 "$APPROVED_STARTUP_PLAN_SHA256" --approve-privileges

The following is a reduced summary of the actual journal and independent readback, rather than the literal JSON output of one command:

{
  "unit": "nginx.service",
  "active": "active",
  "sub": "running",
  "startup": "enabled",
  "startup_journal_steps": 7,
  "http_controls": 20,
  "http_status_counts": {
    "200": 2,
    "400": 3,
    "403": 3,
    "404": 12
  },
  "php_execution_probes": 2,
  "original_files_unchanged": 86,
  "original_journal_files_unchanged": 53
}

Two 200 responses executed PHP in different pools. Other requests checked the default host, method, unexpected query parameters, direct PHP files, path-info, .env and traversal. The /../private.txt check used http.client with an explicit URI, preserving the path before sending it. Original configuration, journals and dpkg state remained unchanged.

This was the start/enable stage before the combined reboot. Acceptance of the new boot follows below.

Nginx after the combined reboot

After starting the timers, we performed one ordinary reboot of the same local VM. A new serial-console login confirmed the machine and changed boot ID. The original NGINX_STARTUP_ARGS remain bound to the boot where start/enable ran; the new console request is passed separately:

deploy-cli host runtime-startup nginx boot-verify "${NGINX_STARTUP_ARGS[@]}" \
  --plan-sha256 "$APPROVED_STARTUP_PLAN_SHA256" \
  --manifest-sha256 "$COMMITTED_STARTUP_MANIFEST_SHA256" \
  --new-boot-request-file "$PRIVATE_DIR/new-boot-console-request.json" \
  --output-file "$PRIVATE_DIR/nginx-new-boot-proof.json"

The reader checked unchanged configuration, startup links and the completed journal. It rebuilt PIDs, sockets and current PHP readiness. Nginx returned automatically as active/running and enabled. All 20 HTTP checks again produced the expected result: two 200 responses executed PHP in separate pools, three responses were 400, three were 403 and twelve were 404. The original /../private.txt URI was again sent through http.client without normalization.

Nginx startup before the combined reboot: live state of two services and explicitly reduced retained HTTP results.
  1. Operations & Security ACLs on Debian: allow public files and protect the private tree
  2. Architecture Nginx on Debian: two public roots and HTTP access checks
  3. Architecture Why Nginx before PHP-FPM: preparing a server for several applications
  4. Operations & Security Two PHP-FPM pools: separate UIDs, Unix sockets and file rights
  5. Platform Engineering First Symfony site on a prepared stack: Composer and file permissions