# ScalPanel mode

URL: https://scalws.com/docs/guide/scalpanel/
Source: `docs/guide/scalpanel.md` in the ScalWS repository

ScalPanel runs every website in its own container and lets the
administrator choose the web server of PHP websites (Admin, Web server, Custom web server).
ScalWS takes that place in **ScalPanel mode**: one `scalwsd` per website container serves
the one website described by the container's `site.json` (ScalPanel's web server contract,
version 1). There is no YAML file in this mode: ScalWS maps every `site.json` field onto its
ordinary configuration keys, so each behaviour on this page is also available to YAML
configurations (see [configuration.md](https://scalws.com/docs/guide/configuration/)).

This page is for ScalPanel administrators and for anyone building ScalPanel site images.
On a server that runs ScalPanel itself (the node), see
[Control panels: ScalPanel hosts](https://scalws.com/docs/guide/control-panels/#scalpanel-hosts).

## How it runs

ScalPanel starts the web server of a website as

```sh
SCALPANEL_SITE_CONFIG=/etc/scalpanel-site/site.json /usr/local/bin/scalpanel-webserver /etc/scalpanel-site/site.json
```

as the website's user (not root, no capabilities), with a read-only root filesystem and
only `/tmp` writable. PHP-FPM runs in the same container on `unix:/tmp/php-fpm.sock`. The
node's edge nginx terminates TLS and sends plain HTTP to the website's `listen` address
with `X-Forwarded-For`, `X-Forwarded-Proto` and `X-ScalPanel-Site: <site id>`. A
configuration change recreates the container; no reload signal is needed.

`scalwsd` chooses its configuration once, in this order:

1. `--site-json <path>` together with `-c`: usage error, exit 2.
2. `--site-json <path>`: ScalPanel mode.
3. The program runs under the name `scalpanel-webserver` (a copy or a link of the binary):
   ScalPanel mode. The path is the one positional argument, else `SCALPANEL_SITE_CONFIG`,
   else `/etc/scalpanel-site/site.json`. No wrapper script is needed. Under any other name
   a positional path is refused (use `--site-json`).
4. `-c <path>` given on the command line or in `SCALWS_CONFIG`: that YAML file, even when
   `SCALPANEL_SITE_CONFIG` is set.
5. `SCALPANEL_SITE_CONFIG` set: ScalPanel mode with that path.
6. Otherwise the YAML file `/etc/scalws/scalws.yaml`.

The names used before ScalPanel's rename (`vpanel-webserver`, `VPANEL_SITE_CONFIG`,
`X-VPanel-Site`, `/etc/vpanel-site`) are not read. `--config-sha256` and
`--previous-config-sha256` apply to YAML files only.

The file is read as a regular file of at most 1 MiB. Unknown fields are ignored at every
level (later contract versions only add fields), `version` must be 1, and the result is
validated like any configuration. Every error is one line starting `site.json:` and the
process exits with 1, so the container restarts and ScalPanel shows the line:

```text
scalwsd: /etc/scalpanel-site/site.json: site.json: limits.timeout_seconds 90000 is larger than 86400 (24 h)
```

`scalwsd --site-json <path> --check` validates a file without serving (`configuration OK`,
or the error line and exit 1). `SIGHUP` re-reads the file; `SIGUSR1` reopens the log
files.

## `--version`

```text
$ scalpanel-webserver --version
scalwsd 1.1.1
site-json: 1
site-json-fields: front_controller,compression,cache,runtime
edge-features: ...
mime-table: 1
```

`site-json:` is the highest contract version this build reads. `site-json-fields:` lists the
optional fields added inside version 1, in the order they were added. Before ScalPanel
writes such a field into a website's `site.json`, it can check that the image's ScalWS lists
it; an older ScalWS ignores a field it does not know. `edge-features:` is for ScalPanel's
node edge ([ScalPanel edge](https://scalws.com/docs/guide/scalpanel-edge/#the-version-line)); `mime-table:` is the
version of the built-in MIME table, which `scalwsd --mime-types` prints.

## site.json fields

The example is ScalPanel's own `site.json` with the three optional fields:

```json
{
  "version": 1,
  "web_server": "custom",
  "site_id": "site_01J...",
  "required_header": { "name": "X-ScalPanel-Site", "value": "site_01J...", "otherwise": 421 },
  "listen": "0.0.0.0:8080",
  "document_root": "/srv/site/public",
  "index": ["index.php", "index.html", "index.htm"],
  "htaccess": "read .htaccess files below document_root as Apache does (AllowOverride All)",
  "front_controller": "/index.php",
  "compression": { "mode": "static", "types": [] },
  "cache": { "enabled": true, "ttl_seconds": 300, "stale_seconds": 60, "memory_mb": 64,
             "bypass_cookies": ["wordpress_logged_in_"], "bypass_paths": ["/wp-admin/"],
             "bypass_query": ["preview"] },
  "php": { "version": "8.3", "fastcgi": "unix:/tmp/php-fpm.sock", "extensions": [".php"],
           "upload_max_mb": 64, "max_execution_seconds": 30 },
  "limits": { "max_body_bytes": 67108864, "timeout_seconds": 90 },
  "security": { "deny_dotfiles": true, "allow_well_known": true, "symlinks": "owner_only" },
  "client_address": { "header": "X-Forwarded-For", "trusted_proxies": ["[redacted address]", "127.0.0.1"] },
  "logs": { "access": "/srv/site/logs/access.log", "access_format": "combined",
            "error": "/srv/site/logs/webserver-error.log" },
  "temp_dir": "/tmp"
}
```

The schema is `scalpanel-site.json`.

| Field | Example | What ScalWS does with it |
|---|---|---|
| `version` | `1` | Must be 1; another value: `site.json: unsupported version 2 (this build reads version 1)`. |
| `web_server`, `site_id` | `"custom"`, `"site_01J..."` | Not used. |
| `required_header` | `{"name": "X-ScalPanel-Site", "value": "site_01J...", "otherwise": 421}` | Every request must carry exactly one such header with exactly this value, else it gets `otherwise` (default 421). See [Required header](#required-header-and-421). Becomes `server.required_header`. |
| `listen` | `"0.0.0.0:8080"` | One plain HTTP listener: `IPv4:port` or `[IPv6]:port`, port not 0. No TLS in this mode. |
| `document_root` | `"/srv/site/public"` | The website's root, served for every host name (`domains: ["*"]`). Absolute, no `..`. |
| `index` | `["index.php", "index.html"]` | Index files in this order. Default `index.php`, `index.html`, `index.htm`. |
| `htaccess` | `"read .htaccess files ..."` | Any non-empty text turns `.htaccess` on, re-checked on every request (`htaccess_recheck: 0s`); empty or absent: off. Password files may lie in `<parent of document_root>/.htpasswds` (`/srv/site/.htpasswds`). See [.htaccess](#htaccess). |
| `front_controller` | `"/index.php"` | Script for paths that do not exist; absent or `""`: off. Starts with `/`, plain path segments only, at most 255 bytes. See [Front controller](#front-controller). |
| `compression` | `{"mode": "static", "types": []}` | `off`, `static` (default, also when the field is absent), `all` or `types` with a `types` list. See [Compression](#compression). |
| `cache` | `{"enabled": true, "ttl_seconds": 300}` | A page cache for PHP responses (and for the application's responses with another [runtime](#runtime) kind); absent or `enabled: false`: none. See [Page cache](#page-cache). |
| `runtime` | `{"kind": "node", "upstream": "unix:/srv/site/tmp/app.sock"}` | Which runtime serves the site; absent: PHP as before. See [Runtime](#runtime). |
| `php` | | Required without `runtime` and with `runtime.kind: php`; not used with another kind. |
| `php.fastcgi` | `"unix:/tmp/php-fpm.sock"` | The PHP-FPM pool: `unix:/path` or `tcp:host:port`. |
| `php.extensions` | `[".php", ".html"]` | Script extensions (ScalPanel's Apache Handlers). Default `[".php"]`; a dot and 1 to 16 lower-case letters or digits, at most 16 entries. See [PHP](#php). |
| `php.upload_max_mb` | `64` | Checked only: a warning when it is larger than `limits.max_body_bytes` (uploads stop at that limit). PHP enforces its own value. |
| `php.max_execution_seconds` | `30` | Checked only: a warning when it is 0 or larger than `limits.timeout_seconds` (ScalWS stops waiting while PHP keeps running). |
| `php.version` | `"8.3"` | Not used. |
| `limits.max_body_bytes` | `67108864` | Largest request body (`server.limits.max_request_body_bytes`); larger gets 413. |
| `limits.timeout_seconds` | `90` | The whole request, 1 to 86400 (0 or absent: no limit). See [Limits](#limits-and-timeouts). |
| `security.deny_dotfiles` | `true` | `true` (default): paths with a segment starting with `.` answer 403, `/.well-known/` excepted. `false`: they answer 404; they are never served either way. |
| `security.allow_well_known` | `true` | `false` adds `/.well-known` to the denied paths (404). Default `true`. |
| `security.symlinks` | `"owner_only"` | `owner_only` (default): a link is followed only when it has the owner of what it points to, else 403. `follow`: links are followed while they stay below the root. `none`: every link answers 403. Any other value is an error. |
| `client_address.header` | `"X-Forwarded-For"` | The header the trusted proxies report the client in (`x-forwarded-for`, `forwarded`, `cf-connecting-ip`, `x-real-ip` or `true-client-ip`, any case). |
| `client_address.trusted_proxies` | `["[redacted address]", "127.0.0.1"]` | Peers believed for the client address and for `X-Forwarded-Proto`. See [Client address and HTTPS](#client-address-and-https). |
| `logs.access`, `logs.access_format` | `"/srv/site/logs/access.log"`, `"combined"` | One Apache combined line per request. Only `combined` is accepted. Absolute path, without a symbolic link on the way (a link, or a linked prefix such as `/var/run`, gives the system's `Too many levels of symbolic links`): use the real path. See [Logs](#logs). |
| `logs.error` | `"/srv/site/logs/webserver-error.log"` | Start-up errors, `.htaccess` warnings, FastCGI failures, one line each. Absolute path, without a symbolic link on the way, as `logs.access`. |
| `temp_dir` | `"/tmp"` | ScalWS's runtime directory is `<temp_dir>/scalws`, and large PHP request bodies are spooled here (see [Limits](#limits-and-timeouts)); under the [sandbox](#sandbox) it is writable. Default `/tmp`. Refused (at start and on reload): `/` or another top-level folder but `/tmp` (such as `/srv`), and a folder that is, holds or lies inside `document_root`, `<parent of document_root>/.htpasswds` or a log file's folder. At start a missing `temp_dir` is created (0700) and tried with a file; when that fails, one warning in `logs.error` says so. |

Fixed in this mode: no admin socket, no metrics listener, cgroups off, no optimizer or local
AI, no ACME, no access log on standard output (the access log goes to `logs.access`), a
directory without an index answers 403 when no front controller takes it
(`indexes: forbidden`), `/healthz` for loopback
peers (`loopback_healthz: true`), 8 MiB for compressed variants
(`server.compression.cache_bytes`), the [sandbox](#sandbox) floor `auto`.

## Runtime

`runtime` says which runtime serves the site. Without it the site is PHP, exactly as before.

```json
"runtime": { "kind": "node", "version": "20", "upstream": "unix:/srv/site/tmp/app.sock",
             "entry": "server.js", "detected": false }
```

| `kind` | What ScalWS does |
|---|---|
| `php` | The `php` block as without `runtime` (`php` is required; `upstream` is refused). |
| `node`, `python`, `ruby`, `container` | `GET` and `HEAD` requests for files that exist under `document_root` are served as files (the `security` rules apply; a folder is served only with an `index.html`), every other request goes to `upstream`, WebSocket upgrades included. The application gets `X-Forwarded-For` and `X-Real-IP` with the resolved client address (as PHP's `REMOTE_ADDR`) and `X-Forwarded-Proto`; `front_controller` and `index` are not used. `upstream` is required. |
| `static` | Files only: a path that is not a file is 404; `front_controller` is ignored (a debug line says so); `upstream` is refused. |

With every kind but `php`, PHP source is never sent: a file ending in `.php`, `.phtml`,
`.php3` to `.php8`, `.phar`, `.phps` or `.inc` (any case) answers 403 (404 with `security.deny_dotfiles: false`, as dotfiles), is not proxied, and is
no index file (with `static`, a folder holding only `index.php` answers 403). The `php`
block, `php.extensions` included, is ignored with these kinds.

`upstream` is where the application listens, as ScalPanel's site owner chose it, so it is
confined:

* `unix:/path`: an absolute path without `..`, inside the site folder (the parent of
  `document_root`, such as `/srv/site` for `/srv/site/public`, not a top-level folder) and
  outside `document_root`; a path that is a symbolic link when the file is read is refused.
* `IP:port`: a loopback address only (`127.0.0.0/8` or `[::1]`), port not 0; host names such
  as `localhost` are refused. Loopback is the site container's own: any port of it is
  allowed.

These checks run when the file is read (start and reload): a socket replaced by a link
later is not noticed. The confinement rests on ScalPanel's model of one scalwsd per site
container, running as the website's user: every socket and port it can reach, the site's
own processes can reach too.

The page `cache` works for these kinds too, but its `bypass_cookies` are usually PHP
applications' cookies: list the application's session cookies (such as `connect.sid` or
`_session_id`), or leave `cache` off, so that pages for a signed-in user are never stored.

`version` (at most 32 bytes), `entry` (at most 255 bytes) and `detected` are informational:
checked for control characters, written once to the log at start (`site.json runtime: kind
node, ...`), never used to choose a binary or a path. ScalWS does not start the application.
Any other `kind` is an error naming `runtime.kind`.

## Sandbox

When neither `SCALWS_SANDBOX_FLOOR` nor `--sandbox-floor` is given, the sandbox floor is
`auto` in this mode: ScalWS applies the [sandbox](https://scalws.com/docs/guide/sandbox/) as `on` where the kernel and
the container allow it. Landlock then lets it write only below `temp_dir` (which holds `<temp_dir>/scalws`), the system temporary directory
(`$TMPDIR`, else `/tmp`), the folders of `logs.access` and `logs.error`, `/var/log/scalws`
and `/var/cache/scalws` when they exist, the folder of `$SCALWS_PERF_REPORT` when it is set,
and the device files `/dev/null`, `/dev/zero`, `/dev/random` and `/dev/urandom`, and run no
program (`temp_dir` is checked so that this never covers the website's files); the seccomp
filter keeps it to the server's system calls. Where something is missing (no
Landlock, a kernel or container seccomp profile that refuses `seccomp()` or the Landlock
calls, arm64, running as root) ScalWS logs one warning naming it and serves without the
sandbox; the start never fails for that reason. The start line says which:

```text
INFO sandbox floor auto (ScalPanel mode): on: Landlock ABI 6 (writes, no exec), seccomp filter
WARN sandbox floor auto (ScalPanel mode): not applied, not available on this kernel (5.10.0): no Landlock; serving without it
```

An explicit floor wins: `SCALWS_SANDBOX_FLOOR=off` (also when set but empty) turns it off
and logs `sandbox floor off (set by SCALWS_SANDBOX_FLOOR or --sandbox-floor ...)` once;
`audit` and `on` work as elsewhere (`on` then fails the start when the filter cannot be
installed). The container shape ScalPanel uses (read-only root filesystem, `--cap-drop
ALL`, the website's user, `no-new-privileges`, Docker's default seccomp profile) runs with
the sandbox in force (`tests/scalpanel/contract.sh`).

PHP is not affected: ScalWS starts no process in this mode. PHP-FPM is started by the
image's entrypoint before ScalWS and talks to it over its socket, so it is not under the
sandbox and writes wherever the website's user may (document root, uploads, sessions,
`upload_tmp_dir`). With the sandbox in force a log folder missing at start is created
(0750) so that it gets its rule, and while Landlock is in force a reload whose `site.json`
moves `temp_dir` or the log files to another folder is refused (`logs.error` says why):
recreate the container instead.

## What a request goes through

1. `GET`/`HEAD` of exactly `/healthz` from the container's own loopback address: answered
   at once (see [/healthz](#healthz)).
2. The client address is resolved (trusted proxies only).
3. The required header: missing, repeated or different gets 421.
4. The scheme: `X-Forwarded-Proto` from a trusted proxy, else plain HTTP.
5. Denied paths, dotfiles (403), `.htaccess` (access, logins, redirects, rewrites, handler
   lines), then the page cache.
6. The PHP handler: a script, a static file, a folder's index or listing, or the front
   controller.
7. `.htaccess` error documents and headers, then compression of a dynamic response
   (`all`, `types`), then the access log line.

The full order with every status code is in
[request-processing.md](https://scalws.com/docs/guide/request-processing/).

## Required header and 421

`required_header` keeps a stale edge route, or a container address that was reused, from
reaching another website's files. A request without the header, with it twice, or with a
different value (compared exactly, so neither case nor trailing spaces are forgiven) gets
the `otherwise` status (421 `Misdirected Request` by default) with a short text body,
before routing, `.htaccess`, files, the page cache or PHP. It is written to the access log
and counted in `scalws_security_blocked_total{reason="required_header"}`. The header stays
visible to PHP (`HTTP_X_SCALPANEL_SITE`).

The header is a routing check, not authentication: the site ID is not a secret. What keeps
other containers away is ScalPanel's network (a site's port is reached only from the edge,
[redacted address], and from the container itself).

An HTTP/1.0 request without `Host` is served too in this mode (routed by the address it
reached), as long as it carries the header.

## Client address and HTTPS

From a peer in `trusted_proxies`, the client is the right-most `X-Forwarded-For` entry that
is not itself a trusted proxy (the edge sends one entry). From any other peer the header is
ignored and the peer is the client. That address is PHP's `REMOTE_ADDR`, the access log's
`%h` and what `.htaccess` `Require ip` compares.

With trusted proxies set, the edge also reports the scheme: exactly one
`X-Forwarded-Proto` value `http` or `https` (any case) from a trusted proxy becomes the
request's scheme. PHP then gets `HTTPS=on`, `REQUEST_SCHEME=https` and `SERVER_PORT=443`
(when the host has no port), `.htaccess` sees `%{HTTPS}` and `%{REQUEST_SCHEME}`, and
absolute redirects use `https://`. This is what keeps WordPress, Laravel and "force HTTPS"
rules from looping. Anything else, or the header from another peer, keeps plain HTTP, and
an `X-Forwarded-Proto` sent by another peer is removed before PHP sees it. (On a YAML
listener with `proxy_protocol`, the peer is the address the PROXY header reports, so the
header counts only when that address is trusted.)

## Front controller

With `front_controller` set, a request that `.htaccess` did not answer goes to the
controller when its path is neither a script, a file nor a folder with an index file, as
nginx's `try_files $uri $uri/ /index.php?$args`. WordPress and Laravel short links work
without any `.htaccess`.

* A `.htaccess` answer wins: a redirect, 403, 401, or a rewrite to a script that exists.
* An existing script runs; an existing file is served; a folder without its trailing slash
  gets 301 to it; a folder with an index file gets the index; a folder without one is
  listed when `Options +Indexes` applies.
* A blocked path never reaches the controller: a dotfile (403), a link `symlinks` refuses
  (403), a denied path (404), a folder with `Options -Indexes` (403), a folder whose
  `.htaccess` denies access.
* Anything else (a missing path, a folder without index or listing) runs the controller
  with `SCRIPT_FILENAME` = `document_root` + `front_controller`, `SCRIPT_NAME` =
  `front_controller`, `REQUEST_URI` = the client's original URI with its query,
  `QUERY_STRING` = the original query (after an `.htaccess` rewrite to a path that does
  not exist: the rewritten query), no `PATH_INFO`.
* A missing controller file answers 404, never 403 or 500. Where `php_flag engine off`
  applies to the controller's folder it answers 403.

Without `front_controller` a missing path is 404 and a folder without an index is 403, as
ScalPanel's nginx answers.

## Compression

`compression.mode` (default `static`):

| Mode | Compressed |
|---|---|
| `static` | Only static files, of text-like types (HTML, CSS, JavaScript, JSON, XML, SVG, plain text, Markdown, CSV, icons, BMP, TTF/OTF, `.eot`, WebAssembly, web manifests). A response of PHP is never compressed, whatever its `Content-Type`, so BREACH cannot apply. A `.html` that runs as PHP is PHP. |
| `all` | Every eligible response, PHP included. |
| `types` | Static and PHP responses whose type is in `types` (`type/subtype`, lower case, without parameters, 1 to 64 entries). |
| `off` | Nothing. |

`all` and `types` compress PHP pages. Do not use them for pages that reflect request input
next to a secret (a CSRF token, for example) unless the application defends against BREACH.

Rules for every mode: gzip and brotli (`br` preferred at equal weight), as the request's
`Accept-Encoding` allows; never for `Range` requests, bodies under 1024 bytes, responses
with their own `Content-Encoding` or `Cache-Control: no-transform`, event streams, images
other than SVG, icons and BMP, audio, video, WOFF/WOFF2, archives and PDF. Every response of
a type the mode compresses carries `Vary: Accept-Encoding`, also when it is sent
uncompressed. Static files are compressed once and kept in memory (8 MiB in this mode);
`.br` and `.gz` files next to a file are sent instead when they are not older. PHP output is
compressed while it streams. The details are in
[ADR-0053](https://scalws.com/docs/adr/0053-response-compression/).

## Page cache

`cache` stores PHP responses in memory, as ScalPanel's nginx page cache does. Static files
are never stored: they are read from disk with zero-copy sending.

| Field | Meaning |
|---|---|
| `enabled` | `true` turns the cache on. |
| `ttl_seconds` | How long a `200` response without caching headers stays fresh; 0 or absent: only responses with their own caching headers are stored. At most one year. |
| `stale_seconds` | How long an expired response may still be served while one request refreshes it. At most one year. |
| `memory_mb` | The website's cache memory, 1 to 1024 (default 64). |
| `bypass_cookies` | Cookie name prefixes: a request with such a cookie skips the cache (`wordpress_logged_in_`). `""` matches every cookie: any request with a cookie skips it. Cookies that match no entry do not stop caching. |
| `bypass_paths` | Path prefixes never cached (`/wp-admin/`). |
| `bypass_query` | Query parameter names that skip the cache (`preview`). |

Cookie and query names are also matched the way PHP reads them: `.`, a space and an
unclosed `[` count as `_`, query names are decoded and `preview[]` is `preview`, so
`wordpress.logged.in_x` skips the cache as `wordpress_logged_in_x` does.

The required header, dotfiles, denied paths, `.htaccess` access rules and logins are
checked before every lookup, so a cached page is never a way around them. A folder whose
`.htaccess` edits a caching header with `Header` (`Cache-Control`, `Pragma`, `Expires`,
`Vary`, `Set-Cookie`) or turns on `ExpiresActive` bypasses the cache: many WordPress
`.htaccess` files have `ExpiresActive On`, and such sites get no page caching. The cache key
holds the `Host`; a page built from another request header (`X-Forwarded-Host`, for example)
without `Vary` would be shared, so the edge should not pass such headers on. There is no
purge command; recreating the container empties the cache. More in
[caching.md](https://scalws.com/docs/guide/caching/#scalpanel-mode).

## `.htaccess`

ScalWS reads the subset of Apache's `.htaccess` described in
[the how-to](https://scalws.com/docs/howto/htaccess/) and [ADR-0031](https://scalws.com/docs/adr/0031-htaccess/): mod_rewrite,
`Redirect` and `RedirectMatch`, access rules (`Require`, `Order`/`Allow`/`Deny`), Basic
authentication, `ErrorDocument`, `Header`, `Expires*`, `DirectoryIndex`, `Options
±Indexes`, `AddType`, PHP handler lines and `php_flag engine off`. In this mode a created,
changed or deleted `.htaccess` applies to the next request. Unsupported lines are ignored
with a warning in `logs.error`; an access rule ScalWS cannot evaluate denies the folder
(403) rather than publish what it protects.

Every block ScalPanel writes is supported and tested with the generator's own text, in both
marker spellings (`# BEGIN ScalPanel ...` and the older `# BEGIN vPanel ...`; ScalWS reads
the lines, not the markers), next to WordPress's block:

| ScalPanel feature | Lines | Behaviour |
|---|---|---|
| Directory privacy | `AuthType Basic`, `AuthName`, `AuthUserFile "/srv/site/.htpasswds/..."`, `Require valid-user` | 401 with `WWW-Authenticate: Basic realm="..."` until the right password; bcrypt `$2y$`, SHA-512 crypt `$6$` and `{SHA}`; subfolders inherit it; authentication comes before redirects and WordPress |
| Error pages | `ErrorDocument 403 /error-pages/403.html` (and 400, 401, 404, 410, 429, 500, 502, 503, 504) | The page is the body; the status stays |
| Redirects | `RewriteRule ^old-page/?$ https://example.com/new-page [R=301,L,NE]` | Status and `Location` as Apache, `\%` a literal `%`, the request's query appended only when the target has none, `[L]` stops before WordPress |
| Directory listing | `Options +Indexes` / `Options -Indexes` | A folder without an index file is listed (HTML) or answers 403 |
| MIME types | `AddType text/markdown .md .markdown` | `Content-Type` of static files by their last extension; a later line wins; it beats the built-in table of `scalwsd --mime-types` |

IP blocking, hotlink protection and country blocking are applied by ScalPanel's edge, not
written to `.htaccess`. A customer's own `Require ip`, `Require not ip`,
`Order`/`Allow`/`Deny` and `RewriteCond %{HTTP_REFERER}` lines work too.

## PHP

* A file whose **last** extension is in `php.extensions` is a script: `x.html.jpg` is an
  image. `.htaccess` `AddHandler application/x-httpd-php .html` adds extensions,
  `RemoveHandler .html` removes them in a folder, `SetHandler` inside `<FilesMatch>` works
  as in Apache.
* A name with a line break or NUL never runs and is never served.
* PHP source is never sent: a `.php` file (also one turned off by `RemoveHandler`, also
  where `.php` is not listed) answers 403. Another listed extension turned off by
  `RemoveHandler` is served as a file, as Apache does.
* `php_flag engine off` (or `php_value engine off`) in a folder: no script there runs, also
  with `PATH_INFO` (`/uploads/x.php/extra`): 403.
* Other `php_value`/`php_flag` lines are not passed to PHP in this mode: the external pool's
  base values are unknown (a warning at start says so). ScalPanel sets PHP options in
  `php.ini`.
* The pool must accept every extension a website may run: set
  `security.limit_extensions = ""` (ScalWS decides what runs) or list them; see
  `packaging/scalpanel/php-fpm-scalpanel.conf`.

## Limits and timeouts

`limits.timeout_seconds` bounds the whole request, from the first byte of its head to the
end of its response: with no response yet, PHP's answer is 504; a request body still
arriving gets 408 and the connection closes; a PHP response already being sent is cut and
the connection closes. Static files and page cache hits are not cut: a slow download is
bounded by `write_timeout` (60 s without progress) instead. PHP-FPM keeps running a script after ScalWS
stops waiting: set the pool's `request_terminate_timeout` to `timeout_seconds` plus a few
seconds (for example 95 for 90), so a timed-out script frees its worker.

`limits.max_body_bytes` answers 413 before the body is read when `Content-Length` is too
large, and cuts a body without a length at the limit. PHP request bodies over 64 KiB are
buffered in an unlinked temporary file in `temp_dir` (not `$TMPDIR`) before PHP gets them.

## Logs

`logs.access` gets one Apache combined line per request:

```text
203.0.113.9 - alice [15/Nov/2026:10:00:00 +0000] "GET /a?b=1 HTTP/1.1" 200 512 "https://r.example/" "UA/1.0"
```

`%h` is the client resolved through `trusted_proxies`, `%u` the user of an `.htaccess`
Basic login, `%t` UTC, `%b` `-` for an empty body; quotes, backslashes and bytes outside
printable ASCII are escaped as Apache does, so no value can break a line. `logs.error` gets
one line per warning or error, also written to standard output:

```text
2026-11-15T10:00:00Z WARN scalws_server::htaccess: htaccess: Frobnicate is not supported; ignored tenant=site app=site file=/sub/.htaccess
```

Each line is appended with one `write(2)`; a file moved away, deleted or truncated (by
ScalPanel's rotation) is reopened within a second, and `SIGUSR1` reopens both at once. A
log folder that is missing at start (a volume mounted late) is retried every second; with
the [sandbox](#sandbox) in force ScalWS creates it at start instead.
Details: [Log files](https://scalws.com/docs/guide/logging-metrics/#log-files).

## `/healthz`

```sh
wget -qO- http://127.0.0.1:8080/healthz
```

inside the container answers `ok` (200) while the server runs and `draining` (503) once
it shuts down, with `Content-Type: text/plain; charset=utf-8` and
`Cache-Control: no-store`, without the required header. Only `GET` or `HEAD` of exactly
`/healthz` (no query) whose TCP peer is a loopback address gets this answer, before the
required header, routing and `.htaccess`, and it is not written to the access log. An
address a proxy reports (`X-Forwarded-For`, `Forwarded`, the PROXY protocol) never counts.
A request from the edge reaches the website as usual: without the site header it gets 421,
with it the website's own `/healthz`, if any.

## The site image

`packaging/scalpanel/` in the source holds the recipe:

* `Dockerfile.example` starts `FROM` ScalPanel's PHP site image (one per PHP version),
  copies the static musl `scalwsd` as `/usr/local/bin/scalpanel-webserver`, keeps the base
  image's entrypoint (which starts PHP-FPM) and its label
  `scalpanel.runtime.sessions="1"`, and adds
  `HEALTHCHECK CMD wget -qO- http://127.0.0.1:8080/healthz || exit 1` (busybox `wget` on
  Alpine).
* `php-fpm-scalpanel.conf`: the PHP-FPM settings a site image needs (socket and pid file in
  `/tmp`, errors to standard error, `security.limit_extensions` empty).

```sh
docker build -f Dockerfile.example \
  --build-arg SITE_PHP=<ScalPanel site-php image>:8.3 \
  --build-arg SCALWSD=scalwsd-1.1.1-scalpanel.1-x86_64-linux-musl \
  -t site-php-scalws:8.3 .
```

Check a binary first: `--version` must print `site-json: 1`. Register the image in
ScalPanel (Admin, Web server, Custom web server).

`tests/scalpanel/contract.sh <scalwsd-binary> [--arch amd64|arm64]` builds a throwaway
image from the recipe on an Alpine stand-in for the site image, runs two websites the way
ScalPanel runs them (website user, read-only root, `/tmp` noexec, no capabilities) and
checks ScalPanel's contract (`tests/e2e/webserver.sh`) plus the front controller,
compression, the page cache, `/healthz` and `--version`.

### arm64

ScalPanel mode is part of every `scalwsd` build, so an `aarch64` static musl binary is built
from the same source: `scripts/release-build-scalpanel.sh` makes the binaries and the
`scalws-scalpanel` `.deb` for amd64 and arm64. The contract suite passes on arm64 under
qemu-user binfmt (`--arch arm64`, `SCALPANEL_CONTRACT_SLOW=4`). The sandbox floor is not
available there (its seccomp filters are x86_64 only): the start line is the warning
`sandbox floor auto (ScalPanel mode): not applied, not available on this platform (Linux
x86_64 only); serving without it`, and the website is served. There is no arm64 speed
measurement yet.

## Troubleshooting

* **Every request answers 421.** The edge's `X-ScalPanel-Site` value differs from
  `required_header.value`, the request has no such header, or it has two. The access log
  shows the 421 lines.
* **The container restarts at once.** `site.json` is invalid: the container's output (and
  `logs.error`, when the log folder is writable) has one line `site.json: ...` naming the
  field. A listener that cannot be bound fails the same way.
* **A log file stays empty.** The writer retries every second and warns on standard output
  (`log file <path>: ...; retrying every second`). The folders above the file must exist
  and be writable by the website's user. A path through a symbolic link is refused, also a
  linked prefix such as `/var/run` or a `/home` that is a link
  (`Too many levels of symbolic links`): use the real path.
* **WordPress loops between http and https.** `trusted_proxies` does not hold the edge's
  address, so `X-Forwarded-Proto` is not believed.
* **`PHP base values unknown` at start.** Expected with ScalPanel's external pool:
  `.htaccess` `php_value`/`php_flag` settings are not passed to PHP; `php_flag engine off`
  still turns PHP off.
* **A page is not cached.** A bypass cookie, path or query matched, the folder's
  `.htaccess` edits caching headers or has `ExpiresActive On`, the request passed a Basic
  login, or the response is not cacheable; `X-Cache` says `BYPASS` or `MISS`.

## Limits of this release

* A `front_controller` on a route's own PHP runtime (YAML only; `site.json` maps no routes)
  does not get the checks of the application's controller (denied paths and `.htaccess` of
  its folder).
* When the front controller runs for a missing path, `.htaccess` `php_value` lines come
  from the folders of the requested path, not of the controller (allowlisted keys only, and
  not in ScalPanel mode, which passes none).

## See also

* [Control panels: ScalPanel hosts](https://scalws.com/docs/guide/control-panels/#scalpanel-hosts)
* [configuration.md](https://scalws.com/docs/guide/configuration/): every key this mode sets
* [request-processing.md](https://scalws.com/docs/guide/request-processing/)
* [caching.md](https://scalws.com/docs/guide/caching/#scalpanel-mode)
* [ADR-0031 `.htaccess`](https://scalws.com/docs/adr/0031-htaccess/), [ADR-0053 compression](https://scalws.com/docs/adr/0053-response-compression/)
