---
title: 'Security & Production Deployment'
url: 'http://phramecms.org/docs/security-production'
markdown_url: 'http://phramecms.org/docs/security-production.md'
bundle: guide
section: security
summary: 'Harden PhrameCMS for production: public/ web root isolation, environment flags, Nginx Authorization header forwarding, multi-worker databases, CSRF, and deny-by-default authentication.'
source: 'https://github.com/PhrameCMS/docs/blob/main/guides/security-production.md'
updated_at: '2026-12-04T21:49:38+00:00'
---

# Security & Production Deployment

PhrameCMS ships with deny-by-default authentication, strict Admin UI security headers, CSRF protection, and RFC 9457 error handling. Follow this checklist before exposing a PhrameCMS deployment to production traffic.

## 1. Web Root Isolation (`public/`)

Point your web server document root strictly to `public/` — **never** to the project root. Keep `.env`, `var/`, `vendor/`, `config/`, `src/`, and `bin/` outside the web root, deny dotfiles (except `.well-known`), and only pass `/index.php` to PHP-FPM.

### Reference Nginx + PHP-FPM Configuration

Based directly on `skeleton/docker-dev/nginx/default.conf`, adapted for HTTPS production (behind TLS termination or with Nginx `listen 443 ssl`):

```nginx
server {
    listen 443 ssl;
    server_name cms.example.test;
    server_tokens off;

    root /var/www/phramecms/public;
    index index.php;

    # Block dotfiles (.env, .git, etc.) while allowing ACME /.well-known/
    location ~ /\.(?!well-known(?:/|$)) {
        deny all;
    }

    location / {
        try_files $uri /index.php$is_args$args;
    }

    location ~ ^/index\.php(/|$) {
        include fastcgi_params;
        fastcgi_pass unix:/run/php/php8.5-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        # Critical: forward Bearer tokens only when present
        fastcgi_param HTTP_AUTHORIZATION $http_authorization if_not_empty;
        internal;
    }

    location ~ \.php$ {
        return 404;
    }
}
```

### Why `if_not_empty` Matters for `HTTP_AUTHORIZATION`

Under Nginx + PHP-FPM, PHP often does not receive the `Authorization` header unless it is explicitly forwarded. However, forwarding an **empty** `HTTP_AUTHORIZATION` parameter can cause PSR-7 request creators to synthesize an empty `Authorization: ` header, which `BearerAuthMiddleware` rejects as malformed even on public routes like `GET /api/v1/openapi.json`.

Always include `if_not_empty`:

```nginx
fastcgi_param HTTP_AUTHORIZATION $http_authorization if_not_empty;
```

## 2. Production Environment Flags

Set these variables in your process environment (process environment variables always take precedence over `.env` in `App\EnvLoader` / `App\AppConfig`):

| Variable | Production Value | Why It Matters |
| :--- | :--- | :--- |
| `PHRAME_DEBUG` | `0` | Keeps `ProblemDetailsResponder` in safe mode: unhandled 500 errors return generic RFC 9457 `application/problem+json` without exception class names, file paths, or stack traces. |
| `PHRAME_ADMIN_SECURE_COOKIE` | `1` | Forces the `Secure` attribute on `/admin` `phrame_session` cookies (passed as `secureCookie: true` to `AdminModule` / `SessionAuthMiddleware`). Essential behind TLS-terminating reverse proxies where PHP sees an `http://` internal request URI. |
| `PHRAME_BASE_URL` | `https://cms.example.test` | Ensures CLI tools such as `./bin/phrame user:login` generate canonical HTTPS URLs. |
| `PHRAME_DSN` | `pgsql://...` or `mysql://...` | Connects to a concurrent multi-worker database server (see below). |
| `PHRAME_DISCOVER_COMPOSER_MODULES` | `1` *(or `0`)* | Set to `0` if you want to strictly pin loaded modules to `config/modules.php` without Composer auto-discovery. |

Never deploy `docker-dev/` to production — it is strictly for local development and can be removed (`rm -rf docker-dev`) from production repositories.

## 3. SQLite vs. PostgreSQL / MariaDB

`PhrameCms\Database\Driver\DbalConnection::fromDsn()` supports `sqlite`/`sqlite3`, `pgsql`/`postgres`/`postgresql`, and `mysql`/`mariadb` DSN schemes:

- **SQLite (`sqlite:<path>`)**: Ideal for local development, CI, and single-process prototypes. Not recommended for concurrent multi-worker PHP-FPM or horizontally scaled production deployments due to single-writer file locking and local-disk state.
- **PostgreSQL (`pgsql://user:<DB_PASSWORD>@db.example.internal:5432/phrame`) or MySQL/MariaDB (`mysql://user:<DB_PASSWORD>@db.example.internal:3306/phrame`)**: Recommended for production multi-worker PHP-FPM and multi-replica deployments.

After provisioning a fresh production database, run `./bin/phrame site:install` (or `./bin/phrame schema:install` for subsequent module additions) and apply your Git-tracked configuration with `./bin/phrame op:run config.import --scopes=config.import`.

## 4. Deny-by-Default Authentication & CSRF Model

PhrameCMS enforces two distinct HTTP authentication boundaries:

### API & HTTP MCP (`BearerAuthMiddleware`)

`UserModule` registers `PhrameCms\User\Http\BearerAuthMiddleware` globally on `HttpKernel` (priority `100`):

- Strips any pre-existing `phrame.actor` request attribute before processing.
- Delegates routes tagged `meta: ['auth' => 'session']` (all authenticated `/admin/*` routes) to `SessionAuthMiddleware`.
- Allows unauthenticated requests **only** when a route is explicitly tagged `meta: ['public' => true]` (such as `GET /api/v1/openapi.json`, `/admin/login`, and `/admin/assets/{file}`) **and** no `Authorization` header was supplied.
- Rejects all other unauthenticated, malformed, duplicate-header, expired, or revoked Bearer requests with `401 Unauthorized` (`application/problem+json` + `WWW-Authenticate: Bearer`).
- Authenticated agent actors execute strictly with their token's `scopes` allowlist through `RbacPolicyEnforcer`.

### Admin UI Sessions, CSRF & Security Headers

All authenticated `/admin/*` routes are guarded by `PhrameCms\User\Http\SessionAuthMiddleware` and `PhrameCms\Admin\Http\AdminSecurityHeadersMiddleware`:

- **Session cookies (`SessionCookie`)**: Issued as `phrame_session` with `HttpOnly; SameSite=Lax; Path=/` plus `Secure` whenever `PHRAME_ADMIN_SECURE_COOKIE=1` (or the request scheme is `https`).
- **CSRF protection**: Every mutating request (`POST`, `PUT`, `PATCH`, `DELETE`) on a session-authenticated route must supply a valid per-session CSRF token in the `_csrf` form field or the `X-CSRF-Token` request header; missing or invalid tokens return `403 Forbidden` (`application/problem+json` + `Cache-Control: no-store`).
- **Security headers (`AdminSecurityHeadersMiddleware`)**: Every `/admin` response automatically includes:
  - `Content-Security-Policy: default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'self'`
  - `X-Frame-Options: DENY`
  - `X-Content-Type-Options: nosniff`
  - `Referrer-Policy: same-origin` (preserving `no-referrer` on sensitive flows like one-time login links)
  - `Cache-Control: no-store` on HTML responses

## 5. Secret Hygiene

- **Never commit secrets or runtime state**: `skeleton/.gitignore` excludes `.env`, `.env.local`, `/var`, and `/vendor`. Verify that `.env`, SQLite files (`var/*.sqlite`), admin passwords, and `phm_agent_` bearer tokens are never committed to Git or placed inside `config/sync/`.
- **Inject secrets via environment or secret manager**: Prefer process-level environment variables (`PHRAME_DSN`, `PHRAME_MCP_TOKEN`) over world-readable files on disk.
- **Least-privilege & rotation**: Issue separate narrowly scoped AI Agent Tokens per integration with explicit `expires_at` dates, use `propose.*` scopes for untrusted or semi-autonomous agents, and revoke unused tokens immediately with `agent_token.revoke`.
- **Audit redaction**: `DatabaseAuditLogger` automatically redacts sensitive metadata keys (`password`, `secret`, `authorization`, and raw `token` fields) before writing to `phrame_audit_log`, while preserving safe operational identifiers (`token_id`, `token_prefix`).

## Related Guides

- [Users, RBAC, and AI Agent Tokens](users-rbac-tokens.md) — Token issuance, scope design, revocation, and audit querying.
- [Configuration Sync](configuration-sync.md) — Safe deployment of Git-tracked configuration via dry-run and atomic imports.
- [Getting Started](getting-started.md) — Initial installation and local verification.
