# ADR-0031: `.htaccess` compatibility (opt-in per application)

URL: https://scalws.com/docs/adr/0031-htaccess/
Source: `docs/adr/0031-htaccess.md` in the ScalWS repository

* Status: Accepted (2026-10-06)

## Context
Hosting customers bring applications written for Apache (WordPress, Laravel, Joomla,
Drupal, …) whose routing, redirects and access rules live in `.htaccess` files they edit
themselves. LiteSpeed and similar servers read them; without that, migrating a site means
rewriting its rules by hand.

## Decision
* `applications[].htaccess: true` (default false) makes scalws read `.htaccess` files from
  the document root down to the requested directory. New crate `scalws-htaccess`: parser and
  evaluator, pure and unit-tested; the pipeline applies the result before the handler.
* Supported (the subset common applications use):
  * mod_rewrite: `RewriteEngine`, `RewriteBase`, `RewriteCond` (server variables,
    `%{HTTP:Header}`, `-f -d -s`, `=`, `<`, `>`, regex, `[NC,OR]`), `RewriteRule`
    with `[L,END,R=code,NC,QSA,QSD,NE,F,G,S=n,C]`; `$n` and `%n` back-references.
  * mod_alias: `Redirect`, `RedirectPermanent`, `RedirectTemp`, `RedirectMatch`.
  * Access: `Require all granted|denied`, `Require [not] ip …`, legacy
    `Order`/`Allow`/`Deny`, inside `<Files>`/`<FilesMatch>` too.
  * `ErrorDocument` (local paths and URLs), `DirectoryIndex`, `Header set|append|unset`,
    `ExpiresActive`/`ExpiresByType`/`ExpiresDefault`, `<IfModule>` (true for the modules
    above; a block for another module is skipped, but access rules in it deny, as below),
    `Options` (since 1.1 `Indexes` lists a folder without an index file, see "ScalPanel
    managed blocks"; other options have no effect).
* Apache semantics kept: rewrite rules apply from the deepest `.htaccess` that has them;
  per-directory patterns match the path relative to that directory; an internal rewrite
  restarts rule processing (at most 10 rounds) unless `[END]`; other directives are merged,
  deeper overriding shallower. The rewritten path re-selects the route of the application;
  `REQUEST_URI` stays the original for PHP.
* Security: the file is written by the tenant:
  * no proxy (`[P]`), no `RewriteMap`, no `php_admin_*`, no `SetHandler`/`AddHandler`:
    such lines are ignored and reported (logs, `scalwsctl` diagnostics);
  * regular expressions use the linear-time `regex` crate; patterns it cannot express
    (back-references inside patterns, look-around) make that rule inactive, not slow;
  * limits: 64 KiB per file, 1000 directives, 10 rewrite rounds; each regular expression
    compiles within 32 KiB, and at most 8 per file within 256 KiB (they run on the shared
    event loops); the parsed-file cache is weighed by compiled size (4 KiB for nearly every
    pattern, so long redirect lists stay cached) and by path length (64 MiB per app); an
    application may spend at most 100 ms per second parsing files: past that, a directory
    whose file is not cached denies until the next second, so the cost stays with that
    tenant; a request's regular expressions, `<FilesMatch>` included, may scan at most
    8 MiB in all rounds, each run costing 4 KiB on top of its subject (about 1 ms; past
    that the request answers 500), and each `<Files>` glob is charged its backtracking
    worst case, name length x pattern length, to the same budget (audit scalpanel N3);
    cached files are weighed by their source, warnings and stored items too;
    `DirectoryIndex` keeps at most 16 names; access rules past the directive or size
    limits deny (a `<Files *>` deny placed after the file's own
    `<Files>` blocks), also below child directories that grant access;
  * a local `ErrorDocument` the deny rules block is not served: the plain error is (the
    path of its URI is checked, without query or fragment); a target that falls back to
    the front controller passes the controller's checks as a request would (its access
    rules, logins and PHP off), and the PHP handler never runs a fallback `.htaccess` did
    not approve for its own controller (404; audit scalpanel N5). The controller checked
    is the one of the runtime serving the path: a route's own PHP runtime, else the
    default one;
  * rewrites stay inside the application; `-f`/`-d` checks use the confined lookup of
    ADR-0006; `.htaccess` itself is never served (dotfiles are 404, or 403 with
    `security.dotfiles: forbidden`, before any file is looked at).
* Cost: parsed files are cached per directory and re-checked (one `statx`) at most every
  2 s, as LiteSpeed does; absent files are cached too. Since 1.1 the interval is the
  application's `htaccess_recheck` (0 to 60 s, default 2 s).

## Consequences
* Unsupported directives are ignored with a warning instead of failing the site, except
  access rules: an access rule scalws cannot evaluate (HTTP authentication other than Basic /
  `Require group|host|env`, access rules inside `<RequireAll>`,
  `<RequireAny>`, `<Limit>`, `<LimitExcept>`, `<If>`, or a `<Files>`/`<FilesMatch>` with
  access rules and a pattern the regex engine cannot take) denies every request to that
  directory (or every name, for the `<Files>` block) with 403. Ignoring it would publish
  what the tenant meant to protect (security audit run-3 C8). The same holds for access
  rules inside `<IfModule>` for a module scalws does not model, after the 1000-directive
  limit, or in the part of a file beyond 64 KiB (run-4), and for `<Files>` blocks inside
  such containers, left open or never closed: they deny every name (run-5).
* A file over 64 KiB is refused as a whole since 1.1 (see "Bounded cost" below).
* `php_value`/`php_flag` were not applied at first; they are since 1.1 (see below).

## 1.1 additions
Basic authentication, `php_value`/`php_flag` and PHP handler lines are now read. Decisions:

* **Access is Apache 2.4's.** `Require` lines and legacy `Order`/`Allow`/`Deny` are separate
  layers combined by `Satisfy` (`all` by default). `Order` with both or neither list
  matching follows Apache, and an unknown `Order` denies. `Allow`/`Deny` entries with host
  names or `env=` are reported and not enforced (denying the scope would lock out every
  visitor). A scope with only negated `Require` lines denies. `RequireAll`, `<Limit>`,
  `AuthType Digest`, `Require group` and other providers still deny (403). `AuthGroupFile`
  alone does not: Apache reads it only for `Require group`.
* **Basic auth.** Formats: bcrypt, `$apr1$`, `$6$`, `$5$` and `{SHA}` (only in `.htaccess`
  user files; a route's `basic_auth` keeps refusing it). `AuthUserFile` must be inside the
  application's `root` or `htpasswd_dirs`, opened with `RESOLVE_BENEATH |
  RESOLVE_NO_SYMLINKS`, a regular file of at most 1 MiB; otherwise 500 with the reason
  logged. A failed login answers 401 with a sanitised realm; an unknown user costs the same
  hash work as a known one. Failures are limited per client (IPv6 per /64) and realm with
  `server.security.htaccess_auth_failures` (default 10 a minute), then 429 without hashing.
  Each application caps concurrent checks and a request waits at most 1 s for a slot, then
  gets 503. No verified-credential cache (new attack surface). `.htaccess` redirects,
  rewrites and `F` answers in a protected directory come after the login. `ErrorDocument
  401` with a remote URL is ignored. `Authorization` is removed before the handler (proxy
  upstreams and PHP); PHP gets `REMOTE_USER` and `AUTH_TYPE=Basic`. The request is
  excluded from the response cache.
* **`php_value`/`php_flag`.** Only the `PHP_VALUE` keys of the base-values list, values
  validated like pool `values` (strings: numbers for `error_reporting`); `php_admin_*` and
  use inside `<Files>` are refused. The whole list is sent on every PHP request of a site
  with `.htaccess`, so a setting never persists in a worker.
* **PHP handlers.** `AddHandler`/`SetHandler`/`AddType`/`ForceType` lines that name PHP,
  including cPanel MultiPHP (`ea-phpNN`, `alt-phpNN`, `___lsphp`), the names hosts use for
  PHP (`x-httpd-php5`, LiteSpeed `lsphp`, `php5-script`, `php-cgi`, mod_fcgid's
  `fcgid-script` for PHP script names) and `proxy:unix:...|fcgi://` to the own pool. Only
  the last extension counts. `SetHandler none|default-handler`, a handler that is clearly
  not PHP (`cgi-script`, `server-status`), a non-PHP `ForceType`, `php_flag engine off` and
  `RemoveHandler`/`RemoveType` of an extension turn PHP off: a built-in script name there
  answers 403 (fail closed; a static `index.html` next to an `index.php` in such a directory
  answers 403 too). A version without a pool, a foreign socket or a TCP `proxy:fcgi://`
  falls back to the own pool with a warning, never to another endpoint (`php.versions`,
  `php.own_version`; `scalwsctl panel check` reports a version).
* **Pools.** Managed pools of `.htaccess` sites run with `security.limit_extensions` empty
  because ScalWS chooses `SCRIPT_FILENAME` (a checked regular file) and the handler lines
  decide what is a script. `cgi.fix_pathinfo` is not set to `0`: it breaks `PATH_INFO` and
  `PHP_SELF` on PHP-FPM 8.5.
* **Panels.** cPanel: version pools from the `ea-phpNN` pool files of the account's user and
  `~/.htpasswds`; DirectAdmin: `domains/<domain>/.htpasswd`, and for a subdomain its parent
  domain's directory. The new parsers have fuzz targets (`htpasswd`,
  `php_value`).

## Bounded cost and broken files (1.1, audit run-7)
* **Broken files answer 500.** Only a missing `.htaccess` is absent. One that exists but
  cannot be opened or read (permissions, I/O error), is not a regular file, is a link the
  confined lookup refuses, is larger than 64 KiB, or exceeds a parse limit stands in as a
  broken file: its directory and every one below answer 500, as Apache answers a broken
  `.htaccess`, and the reason is logged once (per file identity; files that cannot be
  opened are retried at every request). A directory the server can pass through but not
  open (mode 0711) still has its `.htaccess` read. Bytes that are not UTF-8 (a Latin-1 or
  Windows-1254 comment or `AuthName`) are read one character per byte, as Apache reads
  them, so the rules still apply.
* **Parsing is bounded per file.** Each compile attempt is charged by what it costs on the
  Xeon bench host (about 0.1 ms at 4 KiB, 0.2 ms for a pattern that compiles within
  32 KiB, 0.8 ms for one that fails there, up to 3.5 ms at 256 KiB); a file may spend
  about a small pattern per directive plus its eight large ones, and failed large
  compiles count towards the eight. Containers nest at most 16 deep and a file has at most 1000 of them.
  Past a limit the file is broken (500), cached by identity, so it costs once. Parse time
  past the 100 ms per second budget is carried into the next seconds instead of forgotten.
* **Filesystem lookups are charged.** `RewriteCond` file tests and the engine's own
  lookups (`<Files>` names, index files, the PHP handler's walk) are charged to the
  request's scan budget: 32 KiB each (so at most 256 per request) plus 2 KiB per path
  component; past it the request answers 500. The walk for `<Files>` names reuses the
  directories the chain walk found, so its cost is linear in the path. The chain follows
  at most 128 nested directories; a deeper existing one answers 500. Lookups try the
  dentry cache without blocking (`RESOLVE_CACHED`) first and fall back to a short
  blocking lookup, as before.
* **Merged settings are capped.** The files of one path may hold at most 1000 `Header`,
  `ErrorDocument` and `php_value` lines together (what every request merges and applies);
  past that the path answers 500. Access checks read `DirectoryIndex` without merging the
  rest.
* **`/.well-known`.** The chain walks the same segments the file handlers serve, so
  `.htaccess` files under `/.well-known` apply. ACME HTTP-01 answers for pending tokens are
  sent before the `.htaccess` stage, so a tenant file cannot block certificate issuance.

## ScalPanel managed blocks (1.1)
ScalPanel (notes item 5) writes its features into a website's `.htaccess` as blocks between
`# BEGIN ScalPanel <feature> (managed by the panel)` and `# END ScalPanel <feature>`
(`vPanel` in files from before ScalPanel 0.1.29). The lines are ordinary directives: scalws
never looks at the markers. Each block is supported. The integration tests in
`tests/integration/tests/scalpanel_blocks.rs` use the text of ScalPanel 0.1.38's generators
verbatim, in both marker spellings, next to WordPress's own block, on both HTTP stacks:

| Block | Directive lines | Status | Test |
|---|---|---|---|
| Directory privacy | `AuthType Basic`, `AuthName "Members only"`, `AuthUserFile "/srv/site/.htpasswds/public/members/passwd"`, `Require valid-user`; hashes `$2y$` (bcrypt), `$6$` (SHA-512 crypt), `{SHA}` | supported: 401 with the realm until the right password, subfolders inherit it, the user file is never served | `block_password_folders` |
| Error pages | `ErrorDocument 403 /error-pages/403.html`, `ErrorDocument 404 ...`, `ErrorDocument 500 ...` | supported: the page is the body and the status is kept | `block_error_pages` |
| Redirects | `RewriteEngine On`, `RewriteRule ^old-page/?$ https://example.com/new-page [R=301,L,NE]` and the `302`, `$1` and catch-all forms | supported: status and `Location` as Apache, `\%` a literal `%`, `[NE]`, the request's query appended only when the target has none, `[L]` stops before WordPress | `block_redirects` |
| Directory listing | `Options +Indexes`, `Options -Indexes` | supported: listing or 403 for a folder without an index file; without a block the application's `indexes` decides | `block_directory_listing` |
| MIME types | `AddType application/manifest+json .webmanifest`, `AddType text/javascript .mjs`, `AddType text/markdown .md .markdown` | supported: `Content-Type` of static files; a later line wins | `block_mime_types` |
| All of them in one file | privacy, redirects, error pages, WordPress | supported: the login comes first (401 also for a redirected path), then the redirect, then WordPress | `block_combined_file` |

The other lines of notes item 5 are not written by ScalPanel's blocks (IP blocking, hotlink
and country blocking run in ScalPanel's edge), but a customer may write them; they are
supported and tested elsewhere:

| Directive lines | Status | Test |
|---|---|---|
| `Redirect 301 /old /new`, `RedirectMatch` | supported | `scalws-htaccess` `mod_alias_redirects`; `tests/integration/tests/htaccess.rs` `static_site_follows_its_htaccess` |
| `ErrorDocument` for the other codes the panel can write (400, 401, 410, 429, 502, 503, 504) | supported: one rule for every status (a remote URL for 401 is ignored, so the challenge stays) | `scalws-htaccess` `headers_expires_error_documents_and_index`; `htaccess.rs` `basic_auth_protects_a_directory`, `htaccess_answers_come_after_the_login` |
| `Require ip`, `Require not ip`, `Order`/`Allow`/`Deny` | supported | `scalws-htaccess` `access_rules`, `only_negated_require_lines_deny`; contract suite "IP blocker" |
| `RewriteCond %{HTTP_REFERER}` (hotlink protection) | supported | contract suite "hotlink: foreign referer", "hotlink: own referer" |
| `AddHandler application/x-httpd-php .html` (extensions of `php.extensions`), `RemoveHandler` | supported | `htaccess.rs` `addhandler_runs_html_as_php`; `scalpanel.rs` `php_handlers_and_extensions` |
| `Header set`, `Header unset` | supported | `scalws-htaccess` `headers_expires_error_documents_and_index`; contract suite "Header set reaches the client" |

The contract suite is `tests/scalpanel/contract.sh`. Access rules inside `<RequireAll>` and
`<RequireAny>` still deny the folder (403): ScalPanel does not write them.

New in 1.1 with this work:

* **`Options` lists folders.** `Options +Indexes` (also `Options Indexes` and `Options All`,
  which include it; a list without `+`/`-` replaces the inherited set) lists a folder
  without an index file; `-Indexes` answers 403, also where a PHP front controller would
  run. Without either, the application's `indexes` (`not_found` 404, default; `forbidden`
  403, ScalPanel mode) decides, or the front controller runs. The listing is HTML, sorted,
  folders first, with size and modification time; names are HTML-escaped and links
  percent-encoded; dotfiles, links `security.symlinks` refuses, names `deny_paths` denies,
  names never served as files for their suffix (PHP scripts and source such as `.inc`,
  `.phtml`, `.phar`), names `IndexIgnore` hides (`*` and `?` wildcards, the part after a
  last `/`, inherited until `IndexIgnoreReset On`) and names the folder's
  `<Files>`/`<FilesMatch>` rules refuse are left out; at most 10 000 entries and 2 MiB of
  HTML (then a line saying the list was cut); sent with
  `X-Content-Type-Options: nosniff` and a `Content-Security-Policy` without scripts, never
  cached. A subfolder's own `.htaccess` is not read for hiding names. `IndexOptions`,
  `HeaderName` and `ReadmeName` are not supported.
* **`AddType` for other types.** `AddType <type> .ext ...` with a type that is not a PHP
  handler sets the `Content-Type` of static files whose last extension matches; deeper
  files override shallower ones, a later line overrides an earlier one, `RemoveType`
  removes the mapping. A type must be `type/subtype` (token characters, at most 127 bytes)
  with an optional `charset` parameter, else the line is ignored with a warning. PHP types
  stay handler lines (see "1.1 additions").
* **`htaccess_recheck`.** Per application, 0 to 60 s (default 2 s): how long a directory's
  file, or its absence, is trusted before one `statx` checks it again. `0s` (ScalPanel
  mode) checks every directory level on every request, so a created, changed or deleted
  file applies to the next request; parsed files stay cached by identity. A level looked
  up again (any `htaccess_recheck` once it passed) costs 256 bytes of the request's scan
  budget per path component its two lookups resolve (the directory and its `.htaccess`):
  a walk of d levels costs (d + 1)² x 256 bytes, so one walk down 128 levels takes about
  half of it, and a request that walks a path of 127 levels or more twice (one internal
  rewrite), or of about 104 levels three times, answers 500 (audit scalpanel N6).
* **Dotfiles.** With `security.dotfiles: forbidden` a path with a segment starting with `.`
  (but a first `/.well-known`) answers 403 from the `.htaccess` stage and the file handlers,
  before any file is looked at; the front controller never runs for it.
