Internals: decision records
ADR-0031: `.htaccess` compatibility (opt-in per application)
- 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.htaccessfiles from the document root down to the requested directory. New cratescalws-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]),RewriteRulewith[L,END,R=code,NC,QSA,QSD,NE,F,G,S=n,C];$nand%nback-references. - mod_alias:
Redirect,RedirectPermanent,RedirectTemp,RedirectMatch. - Access:
Require all granted|denied,Require [not] ip …, legacyOrder/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.1Indexeslists a folder without an index file, see “ScalPanel managed blocks”; other options have no effect).
- mod_rewrite:
- Apache semantics kept: rewrite rules apply from the deepest
.htaccessthat 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_URIstays the original for PHP. - Security: the file is written by the tenant:
- no proxy (
[P]), noRewriteMap, nophp_admin_*, noSetHandler/AddHandler: such lines are ignored and reported (logs,scalwsctldiagnostics); - regular expressions use the linear-time
regexcrate; 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;DirectoryIndexkeeps 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
ErrorDocumentthe 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.htaccessdid 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/-dchecks use the confined lookup of ADR-0006;.htaccessitself is never served (dotfiles are 404, or 403 withsecurity.dotfiles: forbidden, before any file is looked at).
- no proxy (
- 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’shtaccess_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_flagwere 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.
Requirelines and legacyOrder/Allow/Denyare separate layers combined bySatisfy(allby default).Orderwith both or neither list matching follows Apache, and an unknownOrderdenies.Allow/Denyentries with host names orenv=are reported and not enforced (denying the scope would lock out every visitor). A scope with only negatedRequirelines denies.RequireAll,<Limit>,AuthType Digest,Require groupand other providers still deny (403).AuthGroupFilealone does not: Apache reads it only forRequire group. - Basic auth. Formats: bcrypt,
$apr1$,$6$,$5$and{SHA}(only in.htaccessuser files; a route’sbasic_authkeeps refusing it).AuthUserFilemust be inside the application’srootorhtpasswd_dirs, opened withRESOLVE_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 withserver.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)..htaccessredirects, rewrites andFanswers in a protected directory come after the login.ErrorDocument 401with a remote URL is ignored.Authorizationis removed before the handler (proxy upstreams and PHP); PHP getsREMOTE_USERandAUTH_TYPE=Basic. The request is excluded from the response cache. php_value/php_flag. Only thePHP_VALUEkeys of the base-values list, values validated like poolvalues(strings: numbers forerror_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/ForceTypelines that name PHP, including cPanel MultiPHP (ea-phpNN,alt-phpNN,___lsphp), the names hosts use for PHP (x-httpd-php5, LiteSpeedlsphp,php5-script,php-cgi, mod_fcgid’sfcgid-scriptfor PHP script names) andproxy: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-PHPForceType,php_flag engine offandRemoveHandler/RemoveTypeof an extension turn PHP off: a built-in script name there answers 403 (fail closed; a staticindex.htmlnext to anindex.phpin such a directory answers 403 too). A version without a pool, a foreign socket or a TCPproxy:fcgi://falls back to the own pool with a warning, never to another endpoint (php.versions,php.own_version;scalwsctl panel checkreports a version). - Pools. Managed pools of
.htaccesssites run withsecurity.limit_extensionsempty because ScalWS choosesSCRIPT_FILENAME(a checked regular file) and the handler lines decide what is a script.cgi.fix_pathinfois not set to0: it breaksPATH_INFOandPHP_SELFon PHP-FPM 8.5. - Panels. cPanel: version pools from the
ea-phpNNpool 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
.htaccessis 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.htaccessread. Bytes that are not UTF-8 (a Latin-1 or Windows-1254 comment orAuthName) 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.
RewriteCondfile 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,ErrorDocumentandphp_valuelines together (what every request merges and applies); past that the path answers 500. Access checks readDirectoryIndexwithout merging the rest. /.well-known. The chain walks the same segments the file handlers serve, so.htaccessfiles under/.well-knownapply. ACME HTTP-01 answers for pending tokens are sent before the.htaccessstage, 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:
Optionslists folders.Options +Indexes(alsoOptions IndexesandOptions All, which include it; a list without+/-replaces the inherited set) lists a folder without an index file;-Indexesanswers 403, also where a PHP front controller would run. Without either, the application’sindexes(not_found404, default;forbidden403, 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, linkssecurity.symlinksrefuses, namesdeny_pathsdenies, names never served as files for their suffix (PHP scripts and source such as.inc,.phtml,.phar), namesIndexIgnorehides (*and?wildcards, the part after a last/, inherited untilIndexIgnoreReset 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 withX-Content-Type-Options: nosniffand aContent-Security-Policywithout scripts, never cached. A subfolder’s own.htaccessis not read for hiding names.IndexOptions,HeaderNameandReadmeNameare not supported.AddTypefor other types.AddType <type> .ext ...with a type that is not a PHP handler sets theContent-Typeof static files whose last extension matches; deeper files override shallower ones, a later line overrides an earlier one,RemoveTyperemoves the mapping. A type must betype/subtype(token characters, at most 127 bytes) with an optionalcharsetparameter, 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 onestatxchecks 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 (anyhtaccess_recheckonce 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: forbiddena path with a segment starting with.(but a first/.well-known) answers 403 from the.htaccessstage and the file handlers, before any file is looked at; the front controller never runs for it.