فهرست منبع

feat: static serving is per HOSTNAME - enabled and root, with every field in one place refs SV-132

The ask was to let several hostnames on one project serve different static
files, and to enable or disable serving per host.

EVERY FIELD LIVES IN EXACTLY ONE PLACE AND NO FIELD LIVES IN TWO. `enabled`
and `root` belong to a HOSTNAME, because those are the two questions that
genuinely differ between two names pointed at one project. `mount`, `index` and
`cache_control` stay project-wide, because they are the same answer for every
name and a second copy would be a value to keep in step rather than a
capability.

A hostname's block is AUTHORITATIVE for its two fields: nothing in it is
optional and nothing merges, so a name's behaviour is readable off one object.
`enabled` is therefore REQUIRED within a block - one that left it unsaid would
be the ambiguity per-host authority removes, and defaulting it would unpublish
a site on a PUT that only meant to set a root. There is deliberately NO master
kill switch: a host saying true serves even when the project switch is false,
because an AND would make that field a lie. The cost, stated rather than
discovered: turning off a three-hostname project is three edits.

THE ONE INHERITANCE RULE IS THE COMPATIBILITY RULE. A hostname with no block
of its own follows the project's `enabled` with a root of `/`, which is
byte-identical to the behaviour before this existed, so nothing already
configured changes. Absent is NOT "off on this host".

TWO HOSTNAMES SERVING DIFFERENT TREES NEEDED NO NEW FILE METADATA. A file's
`path` is already a full canonical path and the lookup is already an exact
match on it, so the tree is already expressed by where the file sits; `root` is
that name's document root, prepended to the lookup and invisible in the URL,
exactly like nginx's. Renaming a hostname therefore touches no file. A `site`
label on both host and file was weighed and rejected (a second metadata key,
and every existing file sitting in an unnamed default), as was `host` metadata
on the file (a rename orphans it, and www-plus-apex means naming both). The
root's cost is real and is documented: a file sits at one path, so sharing an
asset between disjoint roots means a shared or nested root, or two copies.

THE WRITE PATHS ARE SPLIT, and the hazard is what decided it. The block is
stored on the hostname entry but is written ONLY by /settings/static, because
the hostnames route replaces its whole list - so an admin editing a
`path_style` and omitting the static block would silently take a live site
down. That route now refuses a `static` key 422 rather than ignoring it,
preserves each surviving name's block across the replacement, and reports it
read-only. On the static route `hostnames` present replaces the whole set and
absent leaves it alone, so a cache_control edit is not a publishing change.

`served` now means SOME name publishes rather than "the project switch is on",
which would have been a confident wrong answer from the moment this shipped.

Falsified three ways, each going red where expected and nowhere else: ignoring
the root reddens 4 and correctly leaves the identity test green, since that
test asserts the case the falsification satisfies; dropping the blocks on a
hostnames PUT reddens exactly the test named for that hazard; ANDing a host's
block with the project switch reddens 5 including the pure one. 1567 tests
pass, 43 new, and every pre-existing static test still green - which is the
compatibility evidence rather than a claim about it.

Also corrects a wrong sentence in openapi.json: the static PUT was documented
as replacing the whole configuration and has always patched. The hostnames
route legitimately carries the same sentence and keeps it, asserted by a
control so the scoped replacement could not bleed.
fszontagh 3 روز پیش
والد
کامیت
4389cfb129

+ 71 - 2
api/llms.txt

@@ -91,7 +91,7 @@ read at startup until something unrelated restarted it.
 
 OFF by default and it needs TWO independent things, neither of which implies
 the other: the request must arrive on a hostname registered to the project,
-AND that project must have static serving explicitly enabled. A project may
+AND serving must be explicitly enabled FOR THAT HOSTNAME. A project may
 hold a hostname and serve nothing; a project may hold files and no hostname, in
 which case they stay private.
 
@@ -101,7 +101,76 @@ turning it on publishes files that were private a moment earlier.
 
 - `GET /api/v1/projects/{p}/settings/static` (admin)
 - `PUT /api/v1/projects/{p}/settings/static` (admin) - body
-  `{"enabled": bool, "mount": "/", "index": "index.html", "cache_control": "public, max-age=300"}`
+  `{"enabled": bool, "mount": "/", "index": "index.html", "cache_control": "public, max-age=300",
+    "hostnames": [{"host": "a.example.com", "enabled": true, "root": "/sites/a"}]}`
+
+### Per hostname: `enabled` and `root`
+
+**EVERY FIELD LIVES IN EXACTLY ONE PLACE.** `enabled` and `root` belong to a
+HOSTNAME; `mount`, `index` and `cache_control` belong to the PROJECT and are
+the same for every one of its names. Nothing is configured twice and nothing
+merges.
+
+A hostname's block is **authoritative** for its two fields. It does not
+inherit, which is why **`enabled` is REQUIRED in a per-host entry** (422
+without it): a block that left it unsaid would unpublish a site on a PUT that
+only meant to set a root.
+
+**A hostname with no block of its own follows the project's `enabled` with a
+root of `/`.** That is the one inheritance rule and it is exactly the behaviour
+before per-host serving existed, so nothing configured earlier changes. Absent
+is NOT "off on this host".
+
+There is **no master kill switch**: a host saying `enabled: true` serves even
+when the project's own `enabled` is false, because an AND would make that field
+a lie. Turning a three-hostname project off is three edits.
+
+In the body, `hostnames` **present REPLACES the whole set of per-host blocks**
+and **absent leaves them alone** - so a PUT carrying only `cache_control` is
+not a publishing change, and an empty array is the only way to return every
+name to the project's switch. A host named there must already be registered to
+the project (422 `unknown_hostname`), since a block on a name the project does
+not hold could never serve anything while reading as though it did.
+
+**`PUT .../settings/hostnames` REFUSES a `static` key** (422
+`unsupported_field`) and must not be used to configure serving, even though the
+block is stored on the hostname entry. That route replaces its whole list, so a
+static block sent with it would be dropped by the next unrelated edit - an
+admin changing a `path_style` would silently take a live site down. It
+preserves each surviving name's block across the replacement and reports it
+read-only; a hostname that is REMOVED takes its block with it.
+
+`served` on the static route means **some hostname publishes**, not "the
+project switch is on". Each entry in its `hostnames` response carries the
+EFFECTIVE `enabled` and `root` for that name plus `configured`, which says
+whether the name was set individually or is following the project.
+
+### `root`: how two hostnames serve different trees
+
+`root` is that hostname's **document root**: prepended to the lookup and
+**invisible in the URL**, exactly like nginx's `root`. With a file stored at
+`/sites/a/index.html` and a host rooted at `/sites/a`, `GET /` serves it.
+
+This needed **no new file metadata**: a file's `path` is already a full path
+and the lookup is already an exact match on it, so the tree is already
+expressed by where the file sits. Renaming a hostname therefore touches no
+file.
+
+Two consequences worth knowing before laying out a tree. The root is not a URL
+prefix, so a host rooted at `/sites/a` asking for `/sites/b/index.html`
+resolves `/sites/a/sites/b/index.html` and gets nothing - **the storage layout
+is not a way around the root.** And a file sits at ONE path, so sharing one
+asset between two **disjoint** roots means giving both hosts the same root,
+nesting one root inside the other, or storing the file twice; there is no way
+for one file to be in two unrelated trees.
+
+A root under `/api`, `/fn` or at `/healthz` is refused 422 `invalid_root` - not
+because it would shadow anything, since a root is a storage prefix and never a
+URL path, but because no file can be STORED at such a path, so the root could
+only ever be empty.
+
+The SPA `index` is resolved **under each host's own root**, so every site gets
+its own index file rather than one shared shell.
 
 `mount` is where the tree appears (`/` or `/something`). A mount under `/api`,
 `/fn` or `/healthz` is refused 422 `invalid_mount`: **the service's own

+ 60 - 12
api/openapi.json

@@ -5406,7 +5406,7 @@
       },
       "put": {
         "summary": "Project hostnames (replace)",
-        "description": "Hostnames this project answers on. A request arriving on one is scoped to THIS project, so this is a tenancy boundary rather than routing. Wildcards are refused here and belong only in certificate selection.\n\nAdmin only. The PUT REPLACES the whole configuration; a partial body drops what it omits.",
+        "description": "Hostnames this project answers on. A request arriving on one is scoped to THIS project, so this is a tenancy boundary rather than routing. Wildcards are refused here and belong only in certificate selection.\n\nAdmin only. The PUT REPLACES the whole configuration; a partial body drops what it omits.\n\nA `static` key on an entry is REFUSED 422 `unsupported_field` rather than ignored: this route replaces the whole list, so a static block sent here would be dropped by the next unrelated edit and a live site would go dark. Configure serving on PUT .../settings/static, whose `hostnames` array carries {host, enabled, root}. Each entry's stored static block IS reported here read-only, and a hostname that is REMOVED takes its block with it.",
         "tags": [
           "projects"
         ],
@@ -5467,7 +5467,7 @@
             "description": "admin key required"
           },
           "422": {
-            "description": "refused: `invalid_hostname` (change the value), `hostname_taken` (another project holds it), `hostname_reserved` (it is the deployment's own admin or global name)"
+            "description": "refused: `invalid_hostname`, `hostname_taken`, `hostname_reserved`, or `unsupported_field` (a `static` key - see the description)"
           }
         }
       }
@@ -5475,7 +5475,7 @@
     "/api/v1/projects/{project}/settings/static": {
       "get": {
         "summary": "Project static file serving (read)",
-        "description": "Serve the project's stored files over HTTP on its own hostname. UNAUTHENTICATED, so it requires BOTH a registered project hostname AND an explicit enable; off by default. The served path of each file comes from its metadata `path`, set with the X-File-Path header at upload; a file without one is not reachable here.",
+        "description": "Serve the project's stored files over HTTP on its own hostnames. UNAUTHENTICATED, so it requires BOTH a registered project hostname AND an explicit enable FOR THAT HOSTNAME; off by default. The served path of each file comes from its metadata `path`, set with the X-File-Path header at upload; a file without one is not reachable here.\n\nPER HOSTNAME: `enabled` and `root` belong to a hostname, while `mount`, `index` and `cache_control` belong to the project and are the same for all of its names - no field is configured in two places. A hostname's block is authoritative and does not inherit, so `enabled` is required within it. A hostname with NO block follows the project's `enabled` with a root of `/`, which is the behaviour before per-host serving existed. There is no master kill switch: a host saying `enabled: true` serves even when the project's own `enabled` is false.",
         "tags": [
           "projects"
         ],
@@ -5521,8 +5521,38 @@
                       "type": "boolean",
                       "description": "Static serving requires at least one project hostname."
                     },
+                    "configured": {
+                      "type": "boolean",
+                      "description": "Whether the project-wide values above are STORED or are the built-in defaults being shown."
+                    },
+                    "hostnames": {
+                      "type": "array",
+                      "description": "EVERY registered hostname, whether or not it carries a block of its own. `enabled` and `root` are the EFFECTIVE values, so a name following the project shows what it will really do; `configured` says whether it was set individually.",
+                      "items": {
+                        "type": "object",
+                        "properties": {
+                          "host": {
+                            "type": "string"
+                          },
+                          "enabled": {
+                            "type": "boolean"
+                          },
+                          "root": {
+                            "type": "string",
+                            "default": "/"
+                          },
+                          "configured": {
+                            "type": "boolean"
+                          },
+                          "served": {
+                            "type": "boolean"
+                          }
+                        }
+                      }
+                    },
                     "served": {
-                      "type": "boolean"
+                      "type": "boolean",
+                      "description": "SOME hostname publishes, not 'the project switch is on' - a project whose own `enabled` is false can still publish one name."
                     }
                   }
                 }
@@ -5536,7 +5566,7 @@
       },
       "put": {
         "summary": "Project static file serving (replace)",
-        "description": "Serve the project's stored files over HTTP on its own hostname. UNAUTHENTICATED, so it requires BOTH a registered project hostname AND an explicit enable; off by default. The served path of each file comes from its metadata `path`, set with the X-File-Path header at upload; a file without one is not reachable here.\n\nAdmin only. The PUT REPLACES the whole configuration; a partial body drops what it omits.",
+        "description": "Serve the project's stored files over HTTP on its own hostnames. UNAUTHENTICATED, so it requires BOTH a registered project hostname AND an explicit enable FOR THAT HOSTNAME; off by default. The served path of each file comes from its metadata `path`, set with the X-File-Path header at upload; a file without one is not reachable here.\n\nPER HOSTNAME: `enabled` and `root` belong to a hostname, while `mount`, `index` and `cache_control` belong to the project and are the same for all of its names - no field is configured in two places. A hostname's block is authoritative and does not inherit, so `enabled` is required within it. A hostname with NO block follows the project's `enabled` with a root of `/`, which is the behaviour before per-host serving existed. There is no master kill switch: a host saying `enabled: true` serves even when the project's own `enabled` is false.\n\nAdmin only. A PARTIAL body patches: an omitted key keeps its stored value. The one exception is `hostnames`, which when PRESENT replaces the whole set of per-host blocks and when ABSENT leaves them alone - so a PUT carrying only `cache_control` is not a publishing change, and an empty array is the only way to return every name to the project's switch. Static config is NOT writable on PUT .../settings/hostnames, which refuses a `static` key 422: that route replaces its whole list, so a block sent there would be dropped by the next unrelated edit and a live site would go dark.",
         "tags": [
           "projects"
         ],
@@ -5577,12 +5607,30 @@
                     "type": "string",
                     "default": "public, max-age=300"
                   },
-                  "has_hostname": {
-                    "type": "boolean",
-                    "description": "Static serving requires at least one project hostname."
-                  },
-                  "served": {
-                    "type": "boolean"
+                  "hostnames": {
+                    "type": "array",
+                    "description": "PER-HOSTNAME blocks. PRESENT replaces the whole set; ABSENT leaves it alone; an empty array returns every name to the project's switch. Each host must already be registered to this project.",
+                    "items": {
+                      "type": "object",
+                      "required": [
+                        "host",
+                        "enabled"
+                      ],
+                      "properties": {
+                        "host": {
+                          "type": "string"
+                        },
+                        "enabled": {
+                          "type": "boolean",
+                          "description": "REQUIRED. A per-host block decides for that host and does not inherit, so it cannot leave this unsaid - defaulting it would unpublish a site on a PUT that only meant to set a root."
+                        },
+                        "root": {
+                          "type": "string",
+                          "default": "/",
+                          "description": "This hostname's document root: prepended to the lookup and INVISIBLE in the URL, like nginx's `root`. With a file stored at /sites/a/index.html and this set to /sites/a, GET / serves it. The storage layout is not a way around it - a host rooted at /sites/a asking for /sites/b/x resolves /sites/a/sites/b/x. A file sits at one path, so sharing an asset between two disjoint roots means a shared or nested root, or storing it twice."
+                        }
+                      }
+                    }
                   }
                 }
               }
@@ -5597,7 +5645,7 @@
             "description": "admin key required"
           },
           "422": {
-            "description": "refused: `invalid_mount` (a mount under /api, /fn or /healthz; the service's own surfaces always win)"
+            "description": "refused: `invalid_mount` (a mount under /api, /fn or /healthz; the service's own surfaces always win), `invalid_root` (a root under /api, /fn or /healthz - no file can be STORED at such a path, so the root could only ever be empty), `unknown_hostname` (a per-host block naming a hostname this project does not hold, which could never serve anything while reading as though it did), or `validation` (a per-host block with no explicit boolean `enabled`)"
           }
         }
       }

+ 122 - 0
docs/superpowers/specs/2026-11-20-static-file-serving-design.md

@@ -128,3 +128,125 @@ function may load into a JS heap, and this path never enters the runtime.
     which is the shadowing regression.
 - Falsification: make the static handler run before the API routes and confirm
   the shadowing test goes red.
+
+---
+
+# Addendum, 2026-11-23: per-hostname serving (SV-132)
+
+Owner's request, 2026-11-20: "if i added plus one or multiple hostname allow to
+configure the static files to which one server. Or allow to multiple hostnames
+can serve different static files / enable or disable per host serving the static
+files".
+
+Everything above still holds. This changes WHERE two of the five values live and
+adds one.
+
+## The split: every field in exactly one place
+
+The decision was shaped by two answers that at first read conflicted - per-host
+config should be complete and authoritative rather than a patch to trace, AND
+`mount`/`index`/`cache_control` should stay in one place. The only shape
+satisfying both is that **no field lives in two places**:
+
+| field | lives on | why there |
+|---|---|---|
+| `enabled` | the **hostname** | the owner's "enable or disable per host" |
+| `root` | the **hostname** | the one value that makes two names different sites |
+| `mount` | the project | the same answer for every name in practice |
+| `index` | the project | ditto |
+| `cache_control` | the project | ditto, and one place to change a cache policy |
+
+A hostname's block is therefore **authoritative for its two fields**: nothing in
+it is optional, nothing merges, and a name's behaviour is readable off one
+object. `enabled` is REQUIRED in a per-host block for exactly that reason - a
+block that left it unsaid would be the ambiguity per-host authority removes, and
+defaulting it would unpublish a site on a PUT that only meant to set a root.
+
+**There is deliberately NO master kill switch.** A host saying `enabled: true`
+IS enabled, with no AND against the project's switch, because an AND would make
+that field a lie in some states. The cost, stated rather than discovered:
+turning off a project with three configured hosts is three edits.
+
+## Compatibility: the one inheritance rule
+
+A hostname with **no block of its own** follows the project's `enabled` with a
+root of `/`. That is byte-identical to the behaviour before this existed, and it
+is the only inheritance in the feature. `effectiveHostStatic()` is the single
+implementation, consulted by both the read path and the host gate so the two
+cannot disagree.
+
+Absent is NOT "off". A stored document written before this feature must come
+back meaning "follow the project", never "off on this host".
+
+## Why two hostnames serving different trees needed NO new file metadata
+
+A file's `path` is already a full canonical path and the lookup is already an
+exact match on it, so **the tree is already expressed by where the file sits in
+it.** The per-host `root` says which part of that tree is this name's document
+root; it is prepended to the lookup and is invisible in the URL, exactly like
+nginx's `root`. So `GET /` on a host rooted at `/sites/a` resolves the file
+stored at `/sites/a/index.html`.
+
+The alternatives were weighed and rejected:
+
+- **a `site` label on both host and file** would let one file belong to many
+  sites and would survive a hostname rename - but it needs a second metadata
+  key, and every existing file would sit in an unnamed default, so a newly named
+  site serves nothing until files are tagged.
+- **`host` metadata on the file** couples the file to a DNS name: a rename
+  orphans every file naming it, and the very common www-plus-apex pair means
+  naming both or storing twice.
+
+The root's cost, stated because it is real: a file sits at one path, so sharing
+one asset between two **disjoint** roots means giving both hosts the same root,
+nesting one inside the other, or storing the file twice. All three are explicit.
+
+A root under `/api`, `/fn` or at `/healthz` is refused - not because it shadows
+anything (a root is a storage prefix and never a URL path) but because
+`staticPathError` refuses to STORE a file at such a path, so the root could only
+ever be permanently empty.
+
+## Which route writes what, and the hazard that decided it
+
+Per-host blocks are **stored on the hostname entry** and **written only by
+`PUT /settings/static`**, whose body gained a `hostnames` array of
+`{host, enabled, root}`.
+
+The hostnames route **refuses** a `static` key with 422 rather than ignoring it,
+and **preserves** each surviving name's block across its replacement. The reason
+is that route's documented replace-the-whole-list semantics: if static config
+were writable there, an admin changing one host's `path_style` and omitting the
+static block would **silently unpublish a live site**. It still REPORTS the
+block read-only, because a hostname list that hid which names publish files
+would conceal the most consequential thing about them.
+
+On the static route, `hostnames` **present replaces the whole set** and
+**absent leaves it alone** - so a PUT of `{"cache_control": ...}` is not a
+publishing change, and an empty array is the only way to express removal. A host
+named there must already be registered to the project: a block on a name the
+project does not hold could never serve anything and would read as though the
+name were published.
+
+`served` on that route now means **"some name publishes"** rather than "the
+project switch is on", since a project whose own `enabled` is false can still
+publish one name. Reporting the switch would have made the field a confident
+wrong answer the moment this shipped.
+
+## Testing
+
+- Pure: `rootError` (including the pairing that `/apiary` and `/sites/api` are
+  fine, so the refusal is selective rather than blanket), `staticLookupAlias`
+  including **the root of `/` being the identity**, which is the compatibility
+  assertion, and `effectiveHostStatic` in both directions.
+- Integration, pairings throughout: two names serving different trees with
+  distinguishable bytes and neither able to reach the other's stored path; a
+  name turned off while its sibling serves, then flipped to prove the switch is
+  what decides; a name publishing while the project switch is off; the
+  path_style edit NOT unpublishing; the refusals with their permitted
+  counterparts.
+- Falsified three ways, all three going red where expected and nowhere else:
+  ignoring the root reddens 4 (and correctly leaves the identity test green,
+  since that test asserts the case the falsification satisfies); dropping the
+  blocks on a hostnames PUT reddens exactly the test named for that hazard;
+  ANDing a host's block with the project switch reddens 5, including the pure
+  one.

+ 155 - 11
src/handlers/project_settings.cpp

@@ -143,6 +143,26 @@ std::optional<int64_t> capFromJson(const nlohmann::json& v, const char* what) {
 /// hold at least one hostname, and `enabled` must be true. An admin who turns
 /// `enabled` on and sees nothing served is otherwise left guessing which of the
 /// three is missing.
+/// The hostname list as the hostnames route reports it, from both the GET and
+/// the PUT so the two cannot drift.
+///
+/// Each entry carries its static block READ ONLY, when it has one. That route
+/// refuses to WRITE the field - it replaces the whole list, so a static block
+/// sent with it would be lost on the next edit - but it must still SHOW it,
+/// because a hostname list that silently omitted which names publish files
+/// would hide the most consequential thing about them.
+nlohmann::json hostListJson(const ProjectSettings* p) {
+    nlohmann::json hosts = nlohmann::json::array();
+    if (!p) return hosts;
+    for (const HostEntry& e : p->hostnames) {
+        nlohmann::json one = {{"host", e.host},
+                              {"path_style", e.pathStyle == PathStyle::Full ? "full" : "short"}};
+        if (e.staticServing) one["static"] = e.staticServing->toJson();
+        hosts.push_back(std::move(one));
+    }
+    return hosts;
+}
+
 nlohmann::json staticViewJson(ServerDeps& d, const std::string& project,
                               const ProjectSettings* p) {
     const StaticConfig cfg = (p && p->staticServing) ? *p->staticServing : StaticConfig{};
@@ -160,7 +180,38 @@ nlohmann::json staticViewJson(ServerDeps& d, const std::string& project,
     // the defaults.
     out["configured"] = p != nullptr && p->staticServing.has_value();
     out["has_hostname"] = hasHost;
-    out["served"] = cfg.enabled && gating && hasHost;
+
+    // EVERY HOSTNAME'S OWN ANSWER, always an array and always complete - every
+    // registered name appears whether or not it carries a block of its own,
+    // because the question an admin actually has is "what does each of my names
+    // do", and a list of only the configured ones cannot answer it.
+    //
+    // `enabled` and `root` here are the EFFECTIVE values, so a name following
+    // the project shows what it will really do rather than a blank. `configured`
+    // is what distinguishes that from a name an admin set individually to the
+    // same values - the same reason the top-level `configured` exists.
+    nlohmann::json hosts = nlohmann::json::array();
+    bool anyServed = false;
+    if (p) {
+        for (const HostEntry& e : p->hostnames) {
+            const HostStatic eff = effectiveHostStatic(p->hostnames, cfg.enabled,
+                                                       normaliseHost(e.host));
+            const bool served = eff.enabled && gating;
+            if (served) anyServed = true;
+            hosts.push_back({{"host", e.host},
+                             {"enabled", eff.enabled},
+                             {"root", eff.root},
+                             {"configured", e.staticServing.has_value()},
+                             {"served", served}});
+        }
+    }
+    out["hostnames"] = std::move(hosts);
+    // ANY hostname serving, not the project switch, because that is now what
+    // the word means: a project whose own `enabled` is false can still publish
+    // one name that says otherwise. Reporting the project switch here would
+    // have made this field a confident wrong answer the moment per-host
+    // serving shipped.
+    out["served"] = anyServed;
     return out;
 }
 
@@ -294,11 +345,7 @@ void registerProjectSettingsRoutes(ApiServer& s) {
         std::string project = projectFor(*d, req, 1);
         requireAdmin(requireKey(*d, req));
         auto proj = d->settings.projectSnapshot(project);
-        nlohmann::json hosts = nlohmann::json::array();
-        if (proj)
-            for (const HostEntry& e : proj->hostnames)
-                hosts.push_back({{"host", e.host},
-                                 {"path_style", e.pathStyle == PathStyle::Full ? "full" : "short"}});
+        nlohmann::json hosts = hostListJson(proj.get());
         // Always an array, and `served` says whether the registry is actually
         // gating - because with no deployment hostnames configured a project
         // hostname is stored and NOT in force, and a list that looked identical
@@ -340,6 +387,20 @@ void registerProjectSettingsRoutes(ApiServer& s) {
                     throw ApiError(ErrCode::Unprocessable, "validation",
                                    "path_style must be 'short' or 'full'; got '" + style + "'");
                 e.pathStyle = style == "full" ? PathStyle::Full : PathStyle::Short;
+                // REFUSED, NOT IGNORED. Static config is stored on the host
+                // entry but is owned by the /settings/static route, because
+                // this list is REPLACED wholesale: accepting `static` here
+                // would mean an admin who edits a path_style and omits it
+                // unpublishes a live site, and ignoring it silently would mean
+                // a caller believing they had configured something. Refusing
+                // what we cannot honour, and naming where it is honoured.
+                if (h.contains("static"))
+                    throw ApiError(ErrCode::Unprocessable, "unsupported_field",
+                                   "static serving is not configured here: this route REPLACES "
+                                   "the hostname list, so a static block sent with it would be "
+                                   "lost on the next edit. Use PUT "
+                                   "/api/v1/projects/{project}/settings/static, whose "
+                                   "'hostnames' array carries {host, enabled, root}");
             } else {
                 throw ApiError(ErrCode::Unprocessable, "validation",
                                "each hostname must be a string or {host, path_style}");
@@ -382,6 +443,17 @@ void registerProjectSettingsRoutes(ApiServer& s) {
         auto current = d->settings.projectSnapshot(project);
         ProjectSettings updated = current ? *current : ProjectSettings{};
         updated.project = project;
+        // CARRY EACH SURVIVING NAME'S STATIC BLOCK ACROSS THE REPLACEMENT.
+        // The list is replaced and the static blocks are not writable here, so
+        // without this every hostname edit would silently unpublish whatever
+        // was being served - which is precisely why the field is refused above
+        // rather than accepted. A name that is REMOVED loses its block with
+        // it, which is correct: the name is gone.
+        for (HostEntry& e : wanted) {
+            const std::string norm = normaliseHost(e.host);
+            for (const HostEntry& was : updated.hostnames)
+                if (normaliseHost(was.host) == norm) { e.staticServing = was.staticServing; break; }
+        }
         updated.hostnames = std::move(wanted);
 
         if (!updated.hasAnyOverrides()) d->settings.removeProject(project);
@@ -389,11 +461,7 @@ void registerProjectSettingsRoutes(ApiServer& s) {
             throw ApiError(ErrCode::Unavailable, "db_error", "could not save project settings");
 
         auto proj = d->settings.projectSnapshot(project);
-        nlohmann::json hosts = nlohmann::json::array();
-        if (proj)
-            for (const HostEntry& e : proj->hostnames)
-                hosts.push_back({{"host", e.host},
-                                 {"path_style", e.pathStyle == PathStyle::Full ? "full" : "short"}});
+        nlohmann::json hosts = hostListJson(proj.get());
         const auto reg = d->settings.hostRegistry();
         sendJson(res, 200, {{"project", project},
                             {"hostnames", std::move(hosts)},
@@ -461,6 +529,82 @@ void registerProjectSettingsRoutes(ApiServer& s) {
         if (const std::string why = mountError(cfg.mount); !why.empty())
             throw ApiError(ErrCode::Unprocessable, "invalid_mount", why);
 
+        // PER-HOSTNAME BLOCKS, written HERE and nowhere else although they are
+        // stored on the hostname entry. The hostnames PUT replaces its whole
+        // list, so a route that both replaced hostnames and carried static
+        // config would unpublish a live site whenever an admin edited a
+        // `path_style` without repeating the static block - so that route
+        // refuses the key outright and this one owns it.
+        //
+        // PRESENT REPLACES THE WHOLE SET; ABSENT LEAVES IT ALONE. A PUT of
+        // `{"enabled": true}` therefore changes only the project switch, while
+        // a PUT carrying `hostnames` defines every per-host block this project
+        // has - any registered name NOT named in the array goes back to
+        // following the project, which is the only way to express removal. Same
+        // trade the hostnames route makes, and said in the API docs rather than
+        // guessed at here.
+        if (body.contains("hostnames")) {
+            if (!body.at("hostnames").is_array())
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "hostnames must be an array of {host, enabled, root}");
+            // host -> block, keyed on the NORMALISED name so that a caller
+            // writing `NT.KB.Example` configures the name they registered.
+            std::unordered_map<std::string, HostStatic> wanted;
+            for (const auto& h : body.at("hostnames")) {
+                if (!h.is_object())
+                    throw ApiError(ErrCode::Unprocessable, "validation",
+                                   "each hostnames entry must be {host, enabled, root}");
+                const std::string raw = h.value("host", std::string());
+                if (raw.empty())
+                    throw ApiError(ErrCode::Unprocessable, "validation",
+                                   "each hostnames entry needs a host");
+                const std::string norm = normaliseHost(raw);
+                // IT MUST BE A NAME THIS PROJECT HOLDS. Configuring static
+                // serving for a hostname the project has not registered would
+                // store a block that can never apply, and - worse - would read
+                // as though the name were published.
+                bool owned = false;
+                for (const HostEntry& e : updated.hostnames)
+                    if (normaliseHost(e.host) == norm) { owned = true; break; }
+                if (!owned)
+                    throw ApiError(ErrCode::Unprocessable, "unknown_hostname",
+                                   "'" + raw + "' is not a hostname registered to project '" +
+                                       project + "': register it on the hostnames route first, "
+                                       "because a static block on a name this project does not "
+                                       "hold could never serve anything");
+
+                HostStatic hs;
+                // `enabled` IS REQUIRED, unlike every other field here. A
+                // per-host block is authoritative for this name - it does not
+                // merge with the project's - so a block that failed to say
+                // whether the name is on is exactly the ambiguity per-host
+                // authority removes, and defaulting it would silently
+                // unpublish a site on a PUT that only meant to set a root.
+                if (!h.contains("enabled") || !h.at("enabled").is_boolean())
+                    throw ApiError(ErrCode::Unprocessable, "validation",
+                                   "hostnames entry for '" + raw +
+                                       "' needs an explicit boolean 'enabled': a per-host block "
+                                       "decides for that host and does not inherit, so it cannot "
+                                       "leave this unsaid");
+                hs.enabled = h.at("enabled").get<bool>();
+                if (h.contains("root")) {
+                    if (!h.at("root").is_string())
+                        throw ApiError(ErrCode::Unprocessable, "validation",
+                                       "root must be a string");
+                    hs.root = normaliseMount(h.at("root").get<std::string>());
+                }
+                if (const std::string why = rootError(hs.root); !why.empty())
+                    throw ApiError(ErrCode::Unprocessable, "invalid_root",
+                                   "'" + raw + "': " + why);
+                wanted[norm] = hs;
+            }
+            for (HostEntry& e : updated.hostnames) {
+                const auto it = wanted.find(normaliseHost(e.host));
+                if (it == wanted.end()) e.staticServing.reset();
+                else e.staticServing = it->second;
+            }
+        }
+
         updated.staticServing = cfg;
         // hasAnyOverrides() counts staticServing, so this cannot delete the
         // document it just wrote - the trap hostnames hit once already.

+ 35 - 14
src/handlers/static_files.cpp

@@ -32,8 +32,8 @@ bool etagMatches(const std::string& header, const std::string& etag) {
 
 } // namespace
 
-bool serveProjectStatic(ServerDeps& d, const std::string& project, const httplib::Request& req,
-                        httplib::Response& res) {
+bool serveProjectStatic(ServerDeps& d, const std::string& project, const std::string& host,
+                        const httplib::Request& req, httplib::Response& res) {
     // GET and HEAD. HEAD was refused at first on the grounds that answering it
     // without a body from a pre-routing response was not something to guess at.
     // That was the wrong trade, reported from a real deployment: a HEAD
@@ -50,12 +50,19 @@ bool serveProjectStatic(ServerDeps& d, const std::string& project, const httplib
     if (req.method != "GET" && !headOnly) return false;
 
     const auto ps = d.settings.projectSnapshot(project);
-    // BOTH conditions, and neither implies the other: the caller has already
+    if (!ps) return false;
+    // THE PROJECT-WIDE HALF: mount, index and cache_control. Absent means never
+    // configured, and then these are the built-in defaults - which is what lets
+    // an admin publish ONE hostname without first configuring the project.
+    // `enabled` is read off it only as the fallback for a host that has no
+    // block of its own.
+    const StaticConfig cfg = ps->staticServing ? *ps->staticServing : StaticConfig{};
+    // THE PER-HOSTNAME HALF: does THIS name publish, and from which root. Both
+    // conditions still hold and neither implies the other - the caller has
     // established that this is a project hostname, and this establishes that
-    // the project has explicitly turned serving on. A project may hold a
-    // hostname and serve no files.
-    if (!ps || !ps->staticServing || !ps->staticServing->enabled) return false;
-    const StaticConfig& cfg = *ps->staticServing;
+    // the name has serving turned on, by its own block or by the project's.
+    const HostStatic hs = effectiveHostStatic(ps->hostnames, cfg.enabled, host);
+    if (!hs.enabled) return false;
 
     // THE SHADOWING RULE. `resolveStaticPath` refuses a service-owned path and
     // a `..` segment before it looks at the mount at all, so `mount: "/"`
@@ -65,13 +72,20 @@ bool serveProjectStatic(ServerDeps& d, const std::string& project, const httplib
     const auto alias = resolveStaticPath(cfg.mount, req.path);
     if (!alias) return false;
 
+    // THE DOCUMENT ROOT, applied after the mount and never before it. The
+    // mount decides whether this request is the tree's to answer at all; the
+    // root decides where in storage the answer lives. A root of `/` is the
+    // identity, which is why every deployment running today is unchanged.
+    const std::string lookup = staticLookupAlias(hs.root, *alias);
+
     FileStore store(d.db);
-    auto file = store.infoByPath(project, *alias);
+    auto file = store.infoByPath(project, lookup);
     if (!file) {
-        // The SPA fallback. NOT a wildcard rewrite: the index file must exist,
-        // and when it does not this is a plain 404.
+        // The SPA fallback, resolved UNDER THIS HOST'S ROOT so each site gets
+        // its own index rather than one shared file. NOT a wildcard rewrite:
+        // the index file must exist, and when it does not this is a plain 404.
         const std::string idx = indexAlias(cfg.index);
-        if (!idx.empty()) file = store.infoByPath(project, idx);
+        if (!idx.empty()) file = store.infoByPath(project, staticLookupAlias(hs.root, idx));
     }
     if (!file) {
         // THE SAME 404 whether the project holds one file or a thousand, and
@@ -129,11 +143,18 @@ bool serveProjectStatic(ServerDeps& d, const std::string& project, const httplib
 /// project-scoped surfaces knows nothing about a mount an admin configured -
 /// and without this the gate would refuse the request before the static
 /// handler ever ran.
-bool projectStaticClaimsPath(ServerDeps& d, const std::string& project,
+bool projectStaticClaimsPath(ServerDeps& d, const std::string& project, const std::string& host,
                              const std::string& path) {
     const auto ps = d.settings.projectSnapshot(project);
-    if (!ps || !ps->staticServing || !ps->staticServing->enabled) return false;
-    return resolveStaticPath(ps->staticServing->mount, path).has_value();
+    if (!ps) return false;
+    const StaticConfig cfg = ps->staticServing ? *ps->staticServing : StaticConfig{};
+    // Asked PER HOSTNAME, exactly as serveProjectStatic asks it. The two must
+    // agree: a path this says is claimed and that one declines to serve falls
+    // through to the router and is answered by the admin web UI's mount, and a
+    // path this declines is 404ed by the gate before the handler ever runs. One
+    // implementation of the decision, consulted twice.
+    if (!effectiveHostStatic(ps->hostnames, cfg.enabled, host).enabled) return false;
+    return resolveStaticPath(cfg.mount, path).has_value();
 }
 
 } // namespace svapi

+ 28 - 3
src/hostnames.cpp

@@ -102,13 +102,13 @@ HostRegistry HostRegistry::build(
     // cannot hand an operator surface to a tenant.
     if (!adminHost.empty()) {
         const std::string h = normaliseHost(adminHost);
-        if (!h.empty()) r.map_[h] = HostBinding{HostKind::Admin, {}, PathStyle::Full};
+        if (!h.empty()) r.map_[h] = HostBinding{HostKind::Admin, {}, PathStyle::Full, h};
     }
     for (const std::string& g : globalHosts) {
         const std::string h = normaliseHost(g);
         if (h.empty()) continue;
         if (r.map_.count(h) != 0) { drop(h); continue; }  // already the admin name
-        r.map_[h] = HostBinding{HostKind::Global, {}, PathStyle::Full};
+        r.map_[h] = HostBinding{HostKind::Global, {}, PathStyle::Full, h};
     }
 
     // Projects. A hostname claimed twice is removed from BOTH claimants, so the
@@ -131,7 +131,7 @@ HostRegistry HostRegistry::build(
                 continue;
             }
             claimant.emplace(h, project);
-            candidate[h] = HostBinding{HostKind::Project, project, e.pathStyle};
+            candidate[h] = HostBinding{HostKind::Project, project, e.pathStyle, h};
         }
     }
     for (const std::string& h : contested) {
@@ -168,6 +168,31 @@ bool isLoopbackAddress(std::string_view localAddr) {
 }
 
 
+HostStatic effectiveHostStatic(const std::vector<HostEntry>& hosts, bool projectEnabled,
+                               std::string_view normalisedHost) {
+    for (const HostEntry& e : hosts) {
+        if (normaliseHost(e.host) != normalisedHost) continue;
+        // ITS OWN BLOCK DECIDES, completely, for both of its fields. No merge
+        // with the project's: that is what "a present block is authoritative"
+        // means, and it is why a host's behaviour is readable off one object.
+        if (e.staticServing) return *e.staticServing;
+        break;
+    }
+    // THE COMPATIBILITY RULE, and the only inheritance in this feature. A name
+    // with no block of its own - which is every name in every deployment
+    // running before this existed - follows the project's `enabled` and serves
+    // the whole tree, which is byte-identical to the previous behaviour.
+    //
+    // Note it also applies to a host that is not in the list at all. That
+    // cannot happen through the registry, which only resolves names it holds,
+    // but a caller passing an unrelated name gets the project default rather
+    // than a silent `enabled = false` that would look like a deliberate denial.
+    HostStatic h;
+    h.enabled = projectEnabled;
+    h.root = "/";
+    return h;
+}
+
 HostClaimRefusal mayClaimHostname(
     std::string_view host, std::string_view project, const std::string& adminHost,
     const std::vector<std::string>& globalHosts,

+ 44 - 0
src/hostnames.hpp

@@ -1,6 +1,9 @@
 #pragma once
 
+#include "static_serve.hpp"
+
 #include <memory>
+#include <optional>
 #include <string>
 #include <string_view>
 #include <unordered_map>
@@ -51,14 +54,55 @@ struct HostBinding {
     std::string project;
     /// Meaningful only when `kind == Project`.
     PathStyle pathStyle = PathStyle::Short;
+    /// The NORMALISED name this binding was resolved by, empty when unknown.
+    ///
+    /// Carried because per-hostname static serving needs to know WHICH of a
+    /// project's names answered, and the alternative is re-normalising the Host
+    /// header at every consumer - two places deriving the same key, which is
+    /// how they come to disagree. It is the registry's own map key, so it
+    /// cannot drift from what resolved.
+    std::string host;
 };
 
 /// One registered hostname, as stored in settings.
 struct HostEntry {
     std::string host;
     PathStyle pathStyle = PathStyle::Short;
+
+    /// This hostname's own static-serving decision, or absent to follow the
+    /// project's.
+    ///
+    /// ABSENT IS NOT "OFF". It means this name has never been configured
+    /// individually and therefore behaves exactly as it did before per-host
+    /// serving existed: the project's `enabled` decides and the document root
+    /// is the whole tree. That is the single inheritance rule in this feature,
+    /// and it is what makes every deployment already running keep working
+    /// untouched - see `effectiveHostStatic`.
+    ///
+    /// WRITTEN BY THE STATIC ROUTE, NOT BY THE HOSTNAMES ROUTE, although it is
+    /// stored here. The hostnames PUT replaces the whole list, so if this were
+    /// writable there an admin changing one host's `path_style` and omitting
+    /// `static` would silently unpublish a live site. The hostnames route
+    /// therefore REFUSES a `static` key rather than ignoring it, reports this
+    /// block read-only, and preserves it for every host that survives the
+    /// replacement.
+    std::optional<HostStatic> staticServing;
 };
 
+/// What static serving does on ONE hostname: its own block when it has one,
+/// otherwise the project-wide `enabled` with the whole tree as its root.
+///
+/// The fallback is the compatibility rule and the only inheritance in this
+/// feature. `projectEnabled` is the project block's own `enabled` - pass false
+/// when the project has no static block at all, which is what "never
+/// configured" has always meant.
+///
+/// `normalisedHost` must already have been through `normaliseHost`; the stored
+/// hosts are normalised here on comparison, so a document carrying
+/// `NT.KB.Example` still matches.
+HostStatic effectiveHostStatic(const std::vector<HostEntry>& hosts, bool projectEnabled,
+                               std::string_view normalisedHost);
+
 /// Lowercase, strip the port, strip one trailing dot.
 ///
 /// The `Host` header is caller-controlled, so every normalisation here is a

+ 16 - 3
src/project_settings.cpp

@@ -48,6 +48,12 @@ ProjectSettings ProjectSettings::fromJson(const nlohmann::json& j) {
                 e.pathStyle = h.value("path_style", std::string("short")) == "full"
                                   ? PathStyle::Full
                                   : PathStyle::Short;
+                // Per-hostname static serving. ABSENT STAYS ABSENT, which is
+                // the compatibility rule rather than a tidiness choice: a
+                // stored document written before this existed must come back
+                // meaning "follow the project", not "off on this host".
+                if (h.contains("static") && h.at("static").is_object())
+                    e.staticServing = HostStatic::fromJson(h.at("static"));
             } else {
                 continue;
             }
@@ -96,9 +102,16 @@ nlohmann::json ProjectSettings::toJson() const {
     // relearning: "no hostnames" and "a server that does not know about
     // hostnames" must not look the same to a reader.
     nlohmann::json hosts = nlohmann::json::array();
-    for (const HostEntry& e : hostnames)
-        hosts.push_back({{"host", e.host},
-                         {"path_style", e.pathStyle == PathStyle::Full ? "full" : "short"}});
+    for (const HostEntry& e : hostnames) {
+        nlohmann::json one = {{"host", e.host},
+                              {"path_style", e.pathStyle == PathStyle::Full ? "full" : "short"}};
+        // Written only when this host was configured individually, so a
+        // round trip cannot pin `enabled: false` onto a name that was simply
+        // following the project - which would read as a deliberate denial and
+        // would stop following a later change to the project's own switch.
+        if (e.staticServing) one["static"] = e.staticServing->toJson();
+        hosts.push_back(std::move(one));
+    }
     j["hostnames"] = std::move(hosts);
     // Written only when configured, so round-tripping a project that never
     // touched this does not pin today's defaults - including `enabled: false`,

+ 2 - 2
src/server.cpp

@@ -529,7 +529,7 @@ void ApiServer::registerRoutes() {
                 // serveProjectStatic() is ever reached, and the feature looks
                 // like it simply does not work.
                 if (!allowed && (req.method == "GET" || req.method == "HEAD") &&
-                    projectStaticClaimsPath(d_, host.project, req.path))
+                    projectStaticClaimsPath(d_, host.project, host.host, req.path))
                     allowed = true;
                 if (!allowed) {
                     sendJson(res, 404, errorBody("not_found", "not served on this host"));
@@ -552,7 +552,7 @@ void ApiServer::registerRoutes() {
             // looks at /api/ paths and those are exactly what the static path
             // refuses to claim.
             if (host.kind == HostKind::Project && req.method != "OPTIONS" &&
-                serveProjectStatic(d_, host.project, req, res))
+                serveProjectStatic(d_, host.project, host.host, req, res))
                 return httplib::Server::HandlerResponse::Handled;
         }
 

+ 4 - 3
src/server.hpp

@@ -220,12 +220,13 @@ void registerFunctionDispatchRoutes(ApiServer&);
 ///
 /// Returns true when it answered (200, 304 or 404 inside a claimed mount), and
 /// false when the request is not this project's static tree to serve.
-bool serveProjectStatic(ServerDeps& d, const std::string& project, const httplib::Request& req,
-                        httplib::Response& res);
+bool serveProjectStatic(ServerDeps& d, const std::string& project, const std::string& host,
+                        const httplib::Request& req, httplib::Response& res);
 
 /// Would `project`'s static mount claim `path`? Used by the host gate, which
 /// must widen its whitelist for a configured mount or it 404s the request
 /// before the handler above is ever reached.
-bool projectStaticClaimsPath(ServerDeps& d, const std::string& project, const std::string& path);
+bool projectStaticClaimsPath(ServerDeps& d, const std::string& project, const std::string& host,
+                             const std::string& path);
 
 } // namespace svapi

+ 49 - 0
src/static_serve.cpp

@@ -70,6 +70,23 @@ nlohmann::json StaticConfig::toJson() const {
             {"cache_control", cacheControl}};
 }
 
+HostStatic HostStatic::fromJson(const nlohmann::json& j) {
+    HostStatic h;
+    if (!j.is_object()) return h;
+    if (j.contains("enabled") && j.at("enabled").is_boolean())
+        h.enabled = j.at("enabled").get<bool>();
+    // Normalised on the way IN as well as out, so a hand-edited document
+    // carrying `root: "/sites/a/"` behaves identically to one written through
+    // the route. An unknown key is ignored, like everywhere else here.
+    if (j.contains("root") && j.at("root").is_string())
+        h.root = normaliseMount(j.at("root").get<std::string>());
+    return h;
+}
+
+nlohmann::json HostStatic::toJson() const {
+    return {{"enabled", enabled}, {"root", root}};
+}
+
 std::string normaliseMount(std::string_view raw) {
     // Surrounding whitespace is a paste artefact, not an intention.
     while (!raw.empty() && std::isspace(static_cast<unsigned char>(raw.front()))) raw.remove_prefix(1);
@@ -169,4 +186,36 @@ std::string staticPathError(const std::string& path) {
     return {};
 }
 
+std::string rootError(const std::string& root) {
+    if (root.empty() || root.front() != '/')
+        return "a document root must start with '/'";
+    if (root.size() > kMaxPathLen)
+        return "a document root may be at most " + std::to_string(kMaxPathLen) + " characters";
+    for (const unsigned char c : root) {
+        if (c < 0x20 || c == 0x7f) return "a document root may not contain control characters";
+        if (c == ' ') return "a document root may not contain spaces";
+        if (c == '?' || c == '#') return "a document root may not contain '?' or '#'";
+    }
+    if (hasDotDotSegment(root)) return "a document root may not contain a '..' segment";
+    // A root no file can ever live under. `staticPathError` refuses to store a
+    // file at a service-owned path, so this root could only ever be empty - and
+    // a permanently empty root accepted with a 200 is a dead end an admin would
+    // have to debug rather than be told about.
+    if (isServiceOwnedPath(root))
+        return "a document root may not sit under '/api', '/fn' or at '/healthz' - no file can "
+               "be stored at such a path, so this root could never name one";
+    return {};
+}
+
+std::string staticLookupAlias(const std::string& root, const std::string& alias) {
+    // `joined(segments(...))` of the concatenation, so a root of "/" and an
+    // alias of "/x" cannot produce "//x", and a root with a trailing slash that
+    // slipped past normalisation cannot either. The root is a STORAGE prefix
+    // and both halves have already been refused a `..` segment, so there is
+    // nothing here that could climb out of it.
+    if (root.empty() || root == "/") return alias;
+    if (alias.empty() || alias == "/") return normaliseMount(root);
+    return normaliseMount(root + alias);
+}
+
 } // namespace svapi

+ 78 - 0
src/static_serve.hpp

@@ -48,6 +48,56 @@ struct StaticConfig {
     nlohmann::json toJson() const;
 };
 
+/// ONE HOSTNAME'S OWN HALF OF THE STATIC CONFIGURATION, and the split between
+/// this and `StaticConfig` is the whole design of per-hostname serving.
+///
+/// Every field lives in exactly one place and no field lives in two. `enabled`
+/// and `root` are per HOSTNAME, because they are the two questions that
+/// genuinely differ between two names pointed at one project: does this name
+/// publish anything, and which subtree is its document root. `mount`, `index`
+/// and `cache_control` stay in `StaticConfig`, project-wide, because they are
+/// the same answer for every name in practice and a second copy of them would
+/// be a value to keep in step rather than a capability.
+///
+/// A present block is COMPLETE and AUTHORITATIVE for its two fields - nothing
+/// inside it is optional and nothing inherits, so a host's behaviour is
+/// readable off one object. The one inheritance rule is at the level above: a
+/// hostname with NO block of its own falls back to the project's `enabled`
+/// with `root` of `/`, which is exactly what this service did before per-host
+/// serving existed. That rule is what makes every deployment already running
+/// keep working untouched, and it is the only reason it exists.
+///
+/// NOTE WHAT THERE IS NOT: no master kill switch. With per-host authority, a
+/// host saying `enabled: true` IS enabled, and turning a three-hostname
+/// project off is three edits. An AND against the project's `enabled` would
+/// have bought one-command revocation at the price of making a host's own
+/// `enabled` a lie in some states, which defeats the point.
+struct HostStatic {
+    /// FALSE by default and it stays false, for the reason `StaticConfig` says:
+    /// turning this on publishes files that were private a moment earlier, so
+    /// it is an act rather than an inherited state.
+    bool enabled = false;
+    /// This hostname's DOCUMENT ROOT: prepended to the looked-up alias and
+    /// INVISIBLE in the URL, so `GET /` on a host rooted at `/sites/a` resolves
+    /// the file stored at `/sites/a/index.html`.
+    ///
+    /// This is why per-hostname trees needed no new file metadata. A stored
+    /// file's `path` is already a full canonical path and the lookup is already
+    /// an exact match on it, so the tree is expressed by WHERE the file sits
+    /// and the root says which part of it is this name's. Renaming a hostname
+    /// therefore touches no file at all.
+    ///
+    /// `/` is the whole tree, which is both the default and the pre-existing
+    /// behaviour. The cost of the choice, stated so nobody rediscovers it: a
+    /// file sits at one path, so sharing one asset between two DISJOINT roots
+    /// means giving both hosts the same root, nesting one inside the other, or
+    /// storing the file twice. All three are explicit; none is silent.
+    std::string root = "/";
+
+    static HostStatic fromJson(const nlohmann::json& j);
+    nlohmann::json toJson() const;
+};
+
 /// The metadata key on a stored file holding the path it is served at.
 ///
 /// Our file NAMES are a single path segment (`[^/]+`, charset-restricted), so
@@ -120,4 +170,32 @@ std::string indexAlias(const std::string& index);
 /// forever.
 std::string staticPathError(const std::string& path);
 
+/// Why this document root may not be used, or empty when it is acceptable.
+///
+/// Takes an ALREADY NORMALISED root, the same contract `mountError` has, so a
+/// caller cannot validate a string it has not yet canonicalised.
+///
+/// A root under `/api`, `/fn` or at `/healthz` is refused - not because it
+/// would shadow anything (a root is a STORAGE prefix and never a URL path, so
+/// it shadows nothing) but because `staticPathError` refuses to store a file at
+/// such a path in the first place, so a root pointing there could only ever
+/// name files that cannot exist. Accepting it would be a 200 for a root that is
+/// permanently empty, which is the kind of silent dead end this service refuses
+/// at write time elsewhere.
+std::string rootError(const std::string& root);
+
+/// The stored `path` this request finally names: the hostname's document root
+/// with the mount-relative alias beneath it.
+///
+/// Separate from `resolveStaticPath` rather than folded into it, because the
+/// two answer different questions and only one of them can refuse: the mount
+/// decides whether the request is this tree's to answer AT ALL (and returns
+/// nullopt when it is not), while the root decides WHERE in storage the answer
+/// lives and can always produce one. Folding them would make a root a reason
+/// to hand the request back to the router, which it must never be.
+///
+/// A root of `/` is the identity, which is what makes every deployment running
+/// today byte-identical in behaviour.
+std::string staticLookupAlias(const std::string& root, const std::string& alias);
+
 } // namespace svapi

+ 293 - 0
tests/test_api_integration.cpp

@@ -6206,3 +6206,296 @@ TEST_F(ApiFixture, ASameOriginGETWithNoOriginHeaderIsRefusedUnlessTheKeyOPTSIN)
     ASSERT_TRUE(f);
     EXPECT_EQ(f->status, 200) << "the normal cross-origin path broke";
 }
+
+// ===========================================================================
+// PER-HOSTNAME STATIC SERVING (SV-132).
+//
+// Pairings throughout, because every one of these could be satisfied by a
+// server that serves nothing: the point is never "this 404s" but "this 404s
+// WHILE its sibling, differing in exactly one configured value, answers 200".
+//
+// Note what cleans up: HostGatingGuard empties the hostname list, and a host
+// removed takes its static block with it, so the per-host state needs no guard
+// of its own.
+// ===========================================================================
+
+namespace {
+
+/// Register two tenant hostnames plus the deployment's own name, so host
+/// gating is in force and both tenant names resolve to this project.
+void twoTenantHosts(int port, const std::string& key, const std::string& project) {
+    httplib::Client c("127.0.0.1", port);
+    c.set_default_headers({{"Authorization", "Bearer " + key}});
+    (void)c.Put(("/api/v1/projects/" + project + "/settings/hostnames").c_str(),
+                nlohmann::json{{"hostnames", {"a.example.com", "b.example.com"}}}.dump(),
+                "application/json");
+    (void)c.Put("/api/v1/settings",
+                nlohmann::json{{"admin_hostname", "admin.example.com"}}.dump(),
+                "application/json");
+}
+
+httplib::Client onHost(int port, const char* host) {
+    httplib::Client c("127.0.0.1", port);
+    c.set_default_headers({{"Host", host}});
+    return c;
+}
+
+} // namespace
+
+TEST_F(ApiFixture, TwoHostnamesServeDIFFERENTTreesAndNeitherCanReachTheOthers) {
+    HostGatingGuard guard{port_, adminKey_, project_};
+    StaticServingGuard sguard{port_, adminKey_, project_};
+    const std::string files = "/api/v1/projects/" + project_ + "/files/";
+    const std::string sbase = "/api/v1/projects/" + project_ + "/settings/static";
+
+    // Two files, in two subtrees, distinguishable by their bytes - because the
+    // failure this test exists to catch is one host answering with the OTHER's
+    // file, and two identical bodies could not tell that from success.
+    ASSERT_EQ(request("PUT", files + "a.html", "SITE-A", "text/html", adminKey_,
+                      {{"X-File-Path", "/sites/a/index.html"}})->status, 201);
+    ASSERT_EQ(request("PUT", files + "b.html", "SITE-B", "text/html", adminKey_,
+                      {{"X-File-Path", "/sites/b/index.html"}})->status, 201);
+    twoTenantHosts(port_, adminKey_, project_);
+    auto put = admin().Put(sbase.c_str(), nlohmann::json{
+        {"enabled", false}, {"mount", "/"}, {"index", "index.html"},
+        {"hostnames", {{{"host", "a.example.com"}, {"enabled", true}, {"root", "/sites/a"}},
+                       {{"host", "b.example.com"}, {"enabled", true}, {"root", "/sites/b"}}}},
+    }.dump(), "application/json");
+    ASSERT_TRUE(put); ASSERT_EQ(put->status, 200) << put->body;
+    // The route reports every name's EFFECTIVE answer, so an admin can read off
+    // what each one does rather than infer it.
+    const auto view = nlohmann::json::parse(put->body);
+    ASSERT_EQ(view.at("hostnames").size(), 2u) << put->body;
+    EXPECT_TRUE(view.at("served").get<bool>())
+        << "`served` must mean 'some name publishes', not 'the project switch is on' - it is off "
+           "here and two names are serving";
+
+    httplib::Client a = onHost(port_, "a.example.com");
+    httplib::Client b = onHost(port_, "b.example.com");
+
+    // THE ROOT IS INVISIBLE: the same request path on two names resolves to two
+    // different stored files.
+    auto ra = a.Get("/");
+    auto rb = b.Get("/");
+    ASSERT_TRUE(ra); ASSERT_TRUE(rb);
+    ASSERT_EQ(ra->status, 200) << ra->body;
+    ASSERT_EQ(rb->status, 200) << rb->body;
+    EXPECT_EQ(ra->body, "SITE-A");
+    EXPECT_EQ(rb->body, "SITE-B") << "one hostname answered with the other's file, which is the "
+                                     "whole failure this feature must not have";
+
+    // AND THE STORAGE PATH IS NOT A URL. Asking host A for B's stored path
+    // resolves under A's root (/sites/a/sites/b/index.html), which exists
+    // nowhere - so the tree layout is not a way around the root. Without the
+    // index disabled this would be the fallback's 200, so it is turned off
+    // first to isolate the arm being tested.
+    ASSERT_EQ(admin().Put(sbase.c_str(), nlohmann::json{{"index", ""}}.dump(),
+                          "application/json")->status, 200);
+    auto crossed = a.Get("/sites/b/index.html");
+    ASSERT_TRUE(crossed);
+    EXPECT_EQ(crossed->status, 404) << "a host reached outside its own document root: "
+                                    << crossed->body;
+
+    admin().Delete((files + "a.html").c_str());
+    admin().Delete((files + "b.html").c_str());
+}
+
+TEST_F(ApiFixture, AHostnameCanBeTurnedOFFWhileItsSiblingKeepsServing) {
+    HostGatingGuard guard{port_, adminKey_, project_};
+    StaticServingGuard sguard{port_, adminKey_, project_};
+    const std::string files = "/api/v1/projects/" + project_ + "/files/";
+    const std::string sbase = "/api/v1/projects/" + project_ + "/settings/static";
+
+    ASSERT_EQ(request("PUT", files + "shared.txt", "SHARED", "text/plain", adminKey_,
+                      {{"X-File-Path", "/shared.txt"}})->status, 201);
+    twoTenantHosts(port_, adminKey_, project_);
+    // The project switch is ON and one name overrides it to off: the "disable
+    // per host" half of the request, which is the direction a merge could not
+    // express.
+    ASSERT_EQ(admin().Put(sbase.c_str(), nlohmann::json{
+        {"enabled", true}, {"mount", "/"},
+        {"hostnames", {{{"host", "b.example.com"}, {"enabled", false}}}},
+    }.dump(), "application/json")->status, 200);
+
+    httplib::Client a = onHost(port_, "a.example.com");
+    httplib::Client b = onHost(port_, "b.example.com");
+    auto served = a.Get("/shared.txt");
+    auto refused = b.Get("/shared.txt");
+    ASSERT_TRUE(served); ASSERT_TRUE(refused);
+    EXPECT_EQ(served->status, 200) << "a name with NO block must still follow the project, which "
+                                      "is the rule every existing deployment relies on: "
+                                   << served->body;
+    EXPECT_EQ(refused->status, 404) << "a name whose own block says false must not serve: "
+                                    << refused->body;
+
+    // THE PAIRING THAT PROVES THE SWITCH IS WHAT DECIDES: flip that one field
+    // and nothing else, and the same request becomes 200. Without this the test
+    // above would pass against a server that 404s b.example.com for any reason
+    // at all.
+    ASSERT_EQ(admin().Put(sbase.c_str(), nlohmann::json{
+        {"hostnames", {{{"host", "b.example.com"}, {"enabled", true}}}},
+    }.dump(), "application/json")->status, 200);
+    auto nowServed = b.Get("/shared.txt");
+    ASSERT_TRUE(nowServed);
+    EXPECT_EQ(nowServed->status, 200) << nowServed->body;
+
+    admin().Delete((files + "shared.txt").c_str());
+}
+
+TEST_F(ApiFixture, AHostnameCanPublishWhileTheProjectSwitchStaysOFF) {
+    HostGatingGuard guard{port_, adminKey_, project_};
+    StaticServingGuard sguard{port_, adminKey_, project_};
+    const std::string files = "/api/v1/projects/" + project_ + "/files/";
+    const std::string sbase = "/api/v1/projects/" + project_ + "/settings/static";
+
+    ASSERT_EQ(request("PUT", files + "one.txt", "ONE", "text/plain", adminKey_,
+                      {{"X-File-Path", "/one.txt"}})->status, 201);
+    twoTenantHosts(port_, adminKey_, project_);
+    ASSERT_EQ(admin().Put(sbase.c_str(), nlohmann::json{
+        {"enabled", false}, {"mount", "/"},
+        {"hostnames", {{{"host", "a.example.com"}, {"enabled", true}}}},
+    }.dump(), "application/json")->status, 200);
+
+    // A host's own `enabled: true` is AUTHORITATIVE: there is deliberately no
+    // AND against the project switch, because that would make this field a lie
+    // in exactly this state. The pairing is the sibling, which follows the
+    // project and therefore serves nothing.
+    auto published = onHost(port_, "a.example.com").Get("/one.txt");
+    auto following = onHost(port_, "b.example.com").Get("/one.txt");
+    ASSERT_TRUE(published); ASSERT_TRUE(following);
+    EXPECT_EQ(published->status, 200) << published->body;
+    EXPECT_EQ(following->status, 404) << following->body;
+
+    admin().Delete((files + "one.txt").c_str());
+}
+
+TEST_F(ApiFixture, AHostnamesPUTPRESERVESAStaticBlockAndREFUSESToWriteOne) {
+    HostGatingGuard guard{port_, adminKey_, project_};
+    StaticServingGuard sguard{port_, adminKey_, project_};
+    const std::string files = "/api/v1/projects/" + project_ + "/files/";
+    const std::string sbase = "/api/v1/projects/" + project_ + "/settings/static";
+    const std::string hbase = "/api/v1/projects/" + project_ + "/settings/hostnames";
+
+    ASSERT_EQ(request("PUT", files + "live.txt", "LIVE", "text/plain", adminKey_,
+                      {{"X-File-Path", "/live.txt"}})->status, 201);
+    twoTenantHosts(port_, adminKey_, project_);
+    ASSERT_EQ(admin().Put(sbase.c_str(), nlohmann::json{
+        {"enabled", false}, {"mount", "/"},
+        {"hostnames", {{{"host", "a.example.com"}, {"enabled", true}}}},
+    }.dump(), "application/json")->status, 200);
+    ASSERT_EQ(onHost(port_, "a.example.com").Get("/live.txt")->status, 200);
+
+    // THE UNPUBLISH HAZARD, and it is the reason the write paths are split.
+    // This route REPLACES the whole list, so an admin editing a path_style
+    // sends no static block - and if that silently dropped it, a live site
+    // would go dark on an unrelated edit.
+    auto edited = admin().Put(hbase.c_str(), nlohmann::json{{"hostnames",
+        {{{"host", "a.example.com"}, {"path_style", "full"}}, {{"host", "b.example.com"}}}}}.dump(),
+        "application/json");
+    ASSERT_TRUE(edited); ASSERT_EQ(edited->status, 200) << edited->body;
+    // Reported read-only here, because a hostname list that hid which names
+    // publish files would conceal the most consequential thing about them.
+    const auto hview = nlohmann::json::parse(edited->body);
+    bool sawBlock = false;
+    for (const auto& h : hview.at("hostnames"))
+        if (h.at("host") == "a.example.com" && h.contains("static")) sawBlock = true;
+    EXPECT_TRUE(sawBlock) << "the hostnames route must SHOW the static block it refuses to write: "
+                          << edited->body;
+    auto stillLive = onHost(port_, "a.example.com").Get("/live.txt");
+    ASSERT_TRUE(stillLive);
+    EXPECT_EQ(stillLive->status, 200)
+        << "editing a path_style unpublished a live site, which is exactly what splitting the "
+           "write paths is for: " << stillLive->body;
+
+    // REFUSED, NOT IGNORED. A silent ignore would let a caller believe they had
+    // configured something; the refusal names the route that honours it.
+    auto rejected = admin().Put(hbase.c_str(), nlohmann::json{{"hostnames",
+        {{{"host", "a.example.com"}, {"static", {{"enabled", true}}}}}}}.dump(),
+        "application/json");
+    ASSERT_TRUE(rejected);
+    EXPECT_EQ(rejected->status, 422) << rejected->body;
+    EXPECT_NE(rejected->body.find("settings/static"), std::string::npos)
+        << "the refusal must say where the field IS honoured: " << rejected->body;
+
+    admin().Delete((files + "live.txt").c_str());
+}
+
+TEST_F(ApiFixture, AStaticBlockForAnUnregisteredHostnameIsRefusedAndARegisteredOneIsNot) {
+    HostGatingGuard guard{port_, adminKey_, project_};
+    StaticServingGuard sguard{port_, adminKey_, project_};
+    const std::string sbase = "/api/v1/projects/" + project_ + "/settings/static";
+    twoTenantHosts(port_, adminKey_, project_);
+
+    // A block on a name the project does not hold could never serve anything,
+    // and - worse - would read as though the name were published.
+    auto bad = admin().Put(sbase.c_str(), nlohmann::json{
+        {"hostnames", {{{"host", "not-ours.example.com"}, {"enabled", true}}}}}.dump(),
+        "application/json");
+    ASSERT_TRUE(bad);
+    EXPECT_EQ(bad->status, 422) << bad->body;
+
+    // PAIRING: a registered name is accepted, so the refusal above is about
+    // ownership rather than about the route refusing every per-host block.
+    auto good = admin().Put(sbase.c_str(), nlohmann::json{
+        {"hostnames", {{{"host", "a.example.com"}, {"enabled", true}}}}}.dump(),
+        "application/json");
+    ASSERT_TRUE(good);
+    EXPECT_EQ(good->status, 200) << good->body;
+
+    // AND `enabled` IS REQUIRED in a per-host block: it is authoritative for
+    // that name and does not inherit, so a block that left it unsaid would
+    // silently unpublish a site on a PUT that only meant to set a root.
+    auto unsaid = admin().Put(sbase.c_str(), nlohmann::json{
+        {"hostnames", {{{"host", "a.example.com"}, {"root", "/sites/a"}}}}}.dump(),
+        "application/json");
+    ASSERT_TRUE(unsaid);
+    EXPECT_EQ(unsaid->status, 422) << unsaid->body;
+
+    // A root that no file could ever be stored under is refused too, with its
+    // own slug, because the remedy is to pick a different root rather than to
+    // fix a payload.
+    auto badRoot = admin().Put(sbase.c_str(), nlohmann::json{
+        {"hostnames", {{{"host", "a.example.com"}, {"enabled", true}, {"root", "/api"}}}}}.dump(),
+        "application/json");
+    ASSERT_TRUE(badRoot);
+    EXPECT_EQ(badRoot->status, 422) << badRoot->body;
+}
+
+TEST_F(ApiFixture, AnAbsentHostnamesKeyLeavesPerHostBlocksALONEandAnEmptyArrayCLEARSThem) {
+    HostGatingGuard guard{port_, adminKey_, project_};
+    StaticServingGuard sguard{port_, adminKey_, project_};
+    const std::string files = "/api/v1/projects/" + project_ + "/files/";
+    const std::string sbase = "/api/v1/projects/" + project_ + "/settings/static";
+
+    ASSERT_EQ(request("PUT", files + "p.txt", "P", "text/plain", adminKey_,
+                      {{"X-File-Path", "/p.txt"}})->status, 201);
+    twoTenantHosts(port_, adminKey_, project_);
+    ASSERT_EQ(admin().Put(sbase.c_str(), nlohmann::json{
+        {"enabled", false}, {"mount", "/"},
+        {"hostnames", {{{"host", "a.example.com"}, {"enabled", true}}}},
+    }.dump(), "application/json")->status, 200);
+
+    // ABSENT LEAVES ALONE: a PUT of an unrelated field must not disturb which
+    // names publish, or every cache_control edit would be a publishing change.
+    ASSERT_EQ(admin().Put(sbase.c_str(),
+        nlohmann::json{{"cache_control", "public, max-age=60"}}.dump(),
+        "application/json")->status, 200);
+    auto kept = onHost(port_, "a.example.com").Get("/p.txt");
+    ASSERT_TRUE(kept);
+    EXPECT_EQ(kept->status, 200) << kept->body;
+    EXPECT_EQ(kept->get_header_value("Cache-Control"), "public, max-age=60")
+        << "cache_control is PROJECT-WIDE: it lives in one place and applies to every name";
+
+    // PRESENT REPLACES THE WHOLE SET, which is the only way to express removal.
+    // The name goes back to following the project, and the project is off.
+    ASSERT_EQ(admin().Put(sbase.c_str(),
+        nlohmann::json{{"hostnames", nlohmann::json::array()}}.dump(),
+        "application/json")->status, 200);
+    auto cleared = onHost(port_, "a.example.com").Get("/p.txt");
+    ASSERT_TRUE(cleared);
+    EXPECT_EQ(cleared->status, 404) << "an empty hostnames array must clear the per-host blocks, "
+                                      "returning each name to the project's own switch: "
+                                   << cleared->body;
+
+    admin().Delete((files + "p.txt").c_str());
+}

+ 112 - 0
tests/test_hostnames.cpp

@@ -549,3 +549,115 @@ TEST(RawHostname, AnOrdinaryHostnameIsACCEPTED_thePairing) {
     EXPECT_EQ(mayClaimHostname("nt.kb.smartbotics.ai", "p", "admin.example.com", {}, {}),
               HostClaimRefusal::None);
 }
+
+// ===========================================================================
+// PER-HOSTNAME STATIC SERVING: THE ONE INHERITANCE RULE IN THE FEATURE
+// (SV-132).
+//
+// `effectiveHostStatic` is the whole of the compatibility story. Every
+// deployment running before per-host serving existed has hostnames with no
+// static block, and these tests are the assertion that such a deployment
+// behaves IDENTICALLY rather than merely similarly - which is the one thing
+// the owner asked for by name.
+// ===========================================================================
+
+namespace {
+HostEntry plainHost(const char* h) {
+    HostEntry e;
+    e.host = h;
+    return e;
+}
+HostEntry configuredHost(const char* h, bool enabled, const char* root = "/") {
+    HostEntry e;
+    e.host = h;
+    svapi::HostStatic s;
+    s.enabled = enabled;
+    s.root = root;
+    e.staticServing = s;
+    return e;
+}
+} // namespace
+
+TEST(EffectiveHostStatic, AHostWithNoBlockFollowsTheProjectAndServesTheWholeTree) {
+    const std::vector<HostEntry> hosts{plainHost("a.example.com")};
+
+    // THE PAIRING, and it is the compatibility test: the project switch is the
+    // only thing deciding, in BOTH directions. One arm alone would pass
+    // against a function that always answered the same way.
+    const svapi::HostStatic on = svapi::effectiveHostStatic(hosts, true, "a.example.com");
+    EXPECT_TRUE(on.enabled);
+    EXPECT_EQ(on.root, "/") << "the pre-existing behaviour is the whole tree, so the default root "
+                               "must be the identity";
+
+    const svapi::HostStatic off = svapi::effectiveHostStatic(hosts, false, "a.example.com");
+    EXPECT_FALSE(off.enabled);
+}
+
+TEST(EffectiveHostStatic, AHostsOwnBlockDECIDESandDoesNotMergeWithTheProjects) {
+    // Both directions, because per-host AUTHORITY is the design decision and
+    // only one of these would pass against a config that merely ANDed or ORed
+    // the two switches.
+    const std::vector<HostEntry> off{configuredHost("a.example.com", false)};
+    EXPECT_FALSE(svapi::effectiveHostStatic(off, true, "a.example.com").enabled)
+        << "a host saying false must win over a project saying true - this is the 'disable per "
+           "host' half of the owner's request";
+
+    const std::vector<HostEntry> on{configuredHost("a.example.com", true)};
+    EXPECT_TRUE(svapi::effectiveHostStatic(on, false, "a.example.com").enabled)
+        << "a host saying true must win over a project saying false, so one name can be published "
+           "without turning the project on - an AND against the project switch would make a "
+           "host's own 'enabled' a lie here";
+}
+
+TEST(EffectiveHostStatic, OneProjectsHostsAreIndependentOfEachOther) {
+    // The owner's actual ask: several names, different trees, independently
+    // switchable. Asserted together so a change that collapsed them onto one
+    // answer cannot pass.
+    const std::vector<HostEntry> hosts{
+        configuredHost("a.example.com", true, "/sites/a"),
+        configuredHost("b.example.com", true, "/sites/b"),
+        configuredHost("legacy.example.com", false),
+        plainHost("follows.example.com"),
+    };
+    EXPECT_EQ(svapi::effectiveHostStatic(hosts, false, "a.example.com").root, "/sites/a");
+    EXPECT_EQ(svapi::effectiveHostStatic(hosts, false, "b.example.com").root, "/sites/b");
+    EXPECT_FALSE(svapi::effectiveHostStatic(hosts, true, "legacy.example.com").enabled);
+    EXPECT_TRUE(svapi::effectiveHostStatic(hosts, true, "follows.example.com").enabled);
+    EXPECT_EQ(svapi::effectiveHostStatic(hosts, true, "follows.example.com").root, "/");
+}
+
+TEST(EffectiveHostStatic, AStoredHostIsMatchedCaseInsensitivelyLikeEverywhereElse) {
+    // DNS is case-insensitive and the registry resolves by the normalised name,
+    // so a hand-written document carrying mixed case must still match or the
+    // block would silently never apply.
+    const std::vector<HostEntry> hosts{configuredHost("A.Example.COM", true, "/sites/a")};
+    EXPECT_EQ(svapi::effectiveHostStatic(hosts, false, "a.example.com").root, "/sites/a");
+}
+
+TEST(EffectiveHostStatic, AnUnrelatedNameGetsTheProjectDefaultRatherThanASilentDenial) {
+    // Cannot arise through the registry, which only resolves names it holds.
+    // Pinned so that the answer for an unknown name is the project's rule
+    // rather than a false that would read as a deliberate refusal.
+    const std::vector<HostEntry> hosts{configuredHost("a.example.com", false)};
+    EXPECT_TRUE(svapi::effectiveHostStatic(hosts, true, "nobody.example.com").enabled);
+}
+
+TEST(HostRegistryStatic, AResolvedBindingCarriesTheNameItResolvedBy) {
+    // Per-host serving needs to know WHICH name answered, and the alternative
+    // is re-normalising the Host header at each consumer - two derivations of
+    // one key, which is how they come to disagree. It is the map key itself.
+    std::unordered_map<std::string, std::vector<HostEntry>> byProject;
+    byProject["novitax"] = {plainHost("nt.kb.example.com")};
+    const HostRegistry r = HostRegistry::build("admin.example.com", {}, byProject);
+
+    const HostBinding b = r.resolve("NT.KB.Example.com:8443");
+    EXPECT_EQ(b.kind, HostKind::Project);
+    EXPECT_EQ(b.project, "novitax");
+    EXPECT_EQ(b.host, "nt.kb.example.com")
+        << "normalised, so the consumer never has to normalise it again";
+
+    EXPECT_EQ(r.resolve("admin.example.com").host, "admin.example.com");
+    EXPECT_EQ(r.resolve("nobody.example.com").host, "")
+        << "an unknown host resolves to nothing at all, so a consumer cannot read a name off a "
+           "binding that matched no registration";
+}

+ 128 - 0
tests/test_static_serve.cpp

@@ -237,3 +237,131 @@ TEST(StaticConfigJson, AnUnknownKeyIsIgnoredAndAnAbsentOneKeepsItsDefault) {
     EXPECT_EQ(c.mount, "/") << "an absent key must follow the default, not become empty";
     EXPECT_EQ(c.index, "index.html");
 }
+
+// ===========================================================================
+// PER-HOSTNAME SERVING (SV-132).
+//
+// The split to keep in mind while reading these: `enabled` and `root` are the
+// hostname's, `mount`, `index` and `cache_control` are the project's, and no
+// field lives in two places. The only inheritance is at the level above, in
+// `effectiveHostStatic`, and it exists solely so that every deployment running
+// before this feature keeps behaving identically.
+// ===========================================================================
+
+// --- rootError -------------------------------------------------------------
+
+TEST(StaticRoot, TheWholeTreeIsAcceptableAndIsTheDefault) {
+    EXPECT_EQ(HostStatic{}.root, "/");
+    EXPECT_EQ(rootError("/"), "");
+    EXPECT_EQ(rootError("/sites/a"), "");
+}
+
+TEST(StaticRoot, AnUncanonicalOrDangerousRootIsRefused) {
+    EXPECT_NE(rootError(""), "") << "an empty root is not the same as '/' and must be refused "
+                                    "rather than silently read as the whole tree";
+    EXPECT_NE(rootError("sites/a"), "");
+    EXPECT_NE(rootError("/sites/../a"), "");
+    EXPECT_NE(rootError("/sites/a b"), "");
+    EXPECT_NE(rootError("/sites/a?x"), "");
+    EXPECT_NE(rootError(std::string("/") + std::string(2000, 'x')), "");
+}
+
+TEST(StaticRoot, ARootNoFileCouldEverLiveUnderIsRefused) {
+    // A root is a STORAGE prefix and shadows nothing, so this is not the
+    // shadowing rule wearing a different hat. It is refused because
+    // staticPathError will not store a file at a service-owned path, so such a
+    // root could only ever be permanently empty - and an admin deserves to be
+    // told that now rather than to debug an empty site.
+    EXPECT_NE(rootError("/api"), "");
+    EXPECT_NE(rootError("/api/v1"), "");
+    EXPECT_NE(rootError("/fn"), "");
+    EXPECT_NE(rootError("/healthz"), "");
+    // THE PAIRING, without which the four above would pass against a function
+    // that refuses every root: a name merely STARTING with those letters is
+    // perfectly serviceable.
+    EXPECT_EQ(rootError("/apiary"), "");
+    EXPECT_EQ(rootError("/fnord"), "");
+    EXPECT_EQ(rootError("/healthzz"), "");
+    EXPECT_EQ(rootError("/sites/api"), "")
+        << "the rule is about the FIRST segment: a tenant may legitimately keep a tree of API "
+           "documentation at /sites/api";
+}
+
+// --- staticLookupAlias -----------------------------------------------------
+
+TEST(StaticLookup, TheWholeTreeRootIsTheIDENTITY) {
+    // THE COMPATIBILITY TEST, and the most load-bearing one in this file: every
+    // deployment running today has no root at all, so this is the assertion
+    // that says their behaviour is unchanged rather than merely similar.
+    EXPECT_EQ(staticLookupAlias("/", "/index.html"), "/index.html");
+    EXPECT_EQ(staticLookupAlias("/", "/assets/app.js"), "/assets/app.js");
+    EXPECT_EQ(staticLookupAlias("", "/assets/app.js"), "/assets/app.js")
+        << "an empty root is the identity too, so a hand-edited document cannot change where a "
+           "file is looked up";
+    EXPECT_EQ(staticLookupAlias("/", "/"), "/");
+}
+
+TEST(StaticLookup, ARootIsPrependedAndIsInvisibleInTheRequest) {
+    EXPECT_EQ(staticLookupAlias("/sites/a", "/index.html"), "/sites/a/index.html");
+    EXPECT_EQ(staticLookupAlias("/sites/a", "/assets/app.js"), "/sites/a/assets/app.js");
+    // The mount root itself resolves to the root, which names no file and is
+    // what sends the request on to the index fallback.
+    EXPECT_EQ(staticLookupAlias("/sites/a", "/"), "/sites/a");
+}
+
+TEST(StaticLookup, TwoHostsWithDisjointRootsCannotReachEachOthersFiles) {
+    // THE POINT OF THE WHOLE FEATURE, stated as the property rather than as a
+    // walk through the handler: the same request path under two roots resolves
+    // to two different stored files, and neither can name the other's.
+    const std::string req = "/index.html";
+    EXPECT_EQ(staticLookupAlias("/sites/a", req), "/sites/a/index.html");
+    EXPECT_EQ(staticLookupAlias("/sites/b", req), "/sites/b/index.html");
+    EXPECT_NE(staticLookupAlias("/sites/a", req), staticLookupAlias("/sites/b", req));
+}
+
+TEST(StaticLookup, TheResultIsAlwaysCanonicalWhateverTheStoredHalvesLookLike) {
+    // The alias and the root both arrive canonical through the normal path, so
+    // this is about a hand-edited document: a doubled slash in the result would
+    // silently never match a stored `path`, which is canonical by
+    // staticPathError. Asserted as the property so it cannot be satisfied by
+    // one more example.
+    for (const char* root : {"/sites/a", "/sites/a/", "sites/a", "//sites//a//"}) {
+        const std::string got = staticLookupAlias(normaliseMount(root), "/x/y.png");
+        EXPECT_EQ(got, "/sites/a/x/y.png") << "root spelling: " << root;
+        EXPECT_EQ(normaliseMount(got), got) << "the lookup must already be canonical";
+    }
+}
+
+TEST(StaticLookup, ARootCannotBeClimbedOutOfBecauseNeitherHalfMayCarryDotDot) {
+    // Not a claim that the join defends itself - it is a string concatenation.
+    // The claim is that both of its inputs were already refused a `..`
+    // segment, which is where the defence lives, and this pins that the two
+    // checks really do cover both halves.
+    EXPECT_NE(rootError("/sites/../../etc"), "");
+    EXPECT_FALSE(resolveStaticPath("/", "/../../etc/passwd").has_value());
+    EXPECT_NE(staticPathError("/sites/../a.png"), "");
+}
+
+// --- HostStatic json -------------------------------------------------------
+
+TEST(HostStaticJson, ARoundTripPreservesBothFields) {
+    HostStatic h;
+    h.enabled = true;
+    h.root = "/sites/a";
+    const HostStatic back = HostStatic::fromJson(h.toJson());
+    EXPECT_TRUE(back.enabled);
+    EXPECT_EQ(back.root, "/sites/a");
+}
+
+TEST(HostStaticJson, AnUnnormalisedRootInAHandEditedDocumentIsCanonicalisedOnTheWayIn) {
+    const HostStatic h =
+        HostStatic::fromJson(nlohmann::json{{"enabled", true}, {"root", "sites/a/"}});
+    EXPECT_EQ(h.root, "/sites/a");
+}
+
+TEST(HostStaticJson, AnAbsentFieldKeepsItsDefaultAndAnUnknownOneIsIgnored) {
+    const HostStatic h =
+        HostStatic::fromJson(nlohmann::json{{"written_by_a_newer_server", 7}});
+    EXPECT_FALSE(h.enabled) << "off by default is not negotiable on this surface";
+    EXPECT_EQ(h.root, "/");
+}

+ 28 - 0
webui/src/pages/settings/ProjectHostnamesTab.tsx

@@ -148,6 +148,13 @@ export default function ProjectHostnamesTab() {
     if (!project || !canSave) return
     // The whole list, every time. There is no merge on this route: what is
     // sent becomes what is stored, so anything left out is removed.
+    //
+    // BUILT FIELD BY FIELD AND NEVER BY SPREADING THE ROW THAT WAS READ. The
+    // GET carries each hostname's static block read-only, and this route
+    // REFUSES a `static` key with 422 `unsupported_field` - so `{...r}` here
+    // would turn every save on this tab into a refusal. The server preserves
+    // each surviving name's block across the replacement, which is why there
+    // is nothing to send back.
     const body: ProjectHostname[] = rows.map((r, i) => ({
       host: normalised[i] ?? r.host.trim(),
       path_style: r.path_style,
@@ -294,6 +301,27 @@ export default function ProjectHostnamesTab() {
                   </code>
                 </p>
 
+                {/* WHETHER THIS NAME PUBLISHES FILES, read-only and shown here
+                    on purpose. Static serving is configured on the Static
+                    files tab, but this is the tab an operator opens when they
+                    want to know what a hostname does - and a hostname list
+                    that hid an unauthenticated public surface would conceal
+                    the most consequential thing about it. */}
+                {(() => {
+                  const st = (hostsQuery.data?.hostnames ?? []).find(
+                    (h) => normaliseHostInput(h.host) === norm,
+                  )?.static
+                  if (!st) return null
+                  return (
+                    <p className="text-xs text-amber-400/90" data-testid="hostname-static">
+                      {st.enabled
+                        ? `Serves stored files publicly with no key, rooted at ${st.root}.`
+                        : 'Set NOT to serve files, whatever the project-wide default says.'}{' '}
+                      Change this on the Static files tab; it cannot be edited here.
+                    </p>
+                  )
+                })()}
+
                 {normalisedAway && (
                   <p className="text-xs text-slate-400" data-testid="hostname-normalised">
                     Stored and matched as <code className="text-slate-200">{norm}</code>. A scheme,

+ 203 - 18
webui/src/pages/settings/ProjectStaticTab.tsx

@@ -5,7 +5,7 @@ import { Badge, FormRow, controlCls, SaveButton, Toggle } from '@/components/for
 import { useAuthStore } from '@/stores/authStore'
 import { useToastStore } from '@/stores/toastStore'
 import { ApiError } from '@/types'
-import type { ProjectStaticSettings } from '@/types'
+import type { ProjectStaticHost, ProjectStaticSettings } from '@/types'
 
 /// Serving a project's stored files to the open internet.
 ///
@@ -22,6 +22,11 @@ const DEFAULT_MOUNT = '/'
 const DEFAULT_INDEX = 'index.html'
 const DEFAULT_CACHE_CONTROL = 'public, max-age=300'
 
+/// What one hostname does. `follow` is the absence of a stored block, which is
+/// a distinct state from `off` and must stay distinguishable: it tracks the
+/// project switch, so changing that switch later moves it.
+type HostMode = 'follow' | 'serve' | 'off'
+
 /// The client-side half of the mount rule. The SERVER is the authority and
 /// answers 422 'invalid_mount'; this exists for the person typing, so a wrong
 /// mount is visible before a save rather than after one. The two are not
@@ -52,12 +57,50 @@ export function mountError(raw: string): string | null {
 /// and the mount. This sentence is the safety message of the whole feature: it
 /// is what makes a wrong mount visible to a reviewer, and what makes "enabled"
 /// read as the publishing act it is rather than as a checkbox.
+/// The client-side half of the document-root rule, same contract as
+/// mountError: the SERVER is the authority and answers 422 'invalid_root';
+/// this exists for the person typing.
+///
+/// Note the refusals look like the mount's and are there for a DIFFERENT
+/// reason. A root is a storage prefix and never a URL path, so it shadows
+/// nothing - it is refused under /api, /fn and /healthz because no file can be
+/// STORED at such a path, so the root could only ever be empty.
+export function rootError(raw: string): string | null {
+  const root = raw.trim()
+  if (root === '') return 'Document root is required. Use / to serve the whole tree.'
+  if (!root.startsWith('/')) return 'Document root must begin with a slash, for example /sites/a.'
+  if (root !== '/' && root.endsWith('/')) return 'Document root must not end with a slash. Use /sites/a, not /sites/a/.'
+  if (root.includes('//')) return 'Document root must not contain an empty path segment.'
+  if (/\s/.test(root)) return 'Document root must not contain whitespace.'
+  const segments = root.split('/').filter((x) => x !== '')
+  if (segments.some((x) => x === '..' || x === '.')) return 'Document root must not contain a . or .. segment.'
+  const first = segments[0] ?? ''
+  if (first === 'api' || first === 'fn' || first === 'healthz') {
+    return `Document root may not sit under /${first}: no file can be stored at such a path, so this root could never name one.`
+  }
+  return null
+}
+
 export function servedOrigin(host: string, mount: string): string {
   const m = mount.trim()
   const path = m === '/' || m === '' ? '' : m
   return `https://${host}${path}`
 }
 
+/// Which stored file a request to this hostname's own root resolves to.
+///
+/// Worth showing rather than leaving to be inferred, because the document root
+/// is INVISIBLE in the URL: the whole point of per-host serving is that two
+/// names ask for the same path and get different files, and an admin who
+/// cannot see where a name is pointed cannot tell the two apart.
+export function resolvedExample(root: string, index: string): string {
+  const r = root.trim()
+  const prefix = r === '/' || r === '' ? '' : r
+  const idx = index.trim()
+  const leaf = idx === '' ? '' : (idx.startsWith('/') ? idx : `/${idx}`)
+  return leaf === '' ? `${prefix || '/'} (no index file: an unmatched path is a plain 404)` : `${prefix}${leaf}`
+}
+
 export default function ProjectStaticTab() {
   const admin = useAuthStore((s) => s.admin)
   const project = useAuthStore((s) => s.currentProject)
@@ -86,6 +129,14 @@ export default function ProjectStaticTab() {
   /// has not learned about yet.
   const [serverMountError, setServerMountError] = useState<string | null>(null)
 
+  /// Per-hostname rows, keyed by host. THREE states, not two, because
+  /// "following the project" is a real stored state and not a synonym for off:
+  /// a name with no block of its own follows the project switch, which is
+  /// exactly what every hostname configured before this feature existed does.
+  /// Collapsing it into a boolean would make the UI unable to express - or even
+  /// to display - the state most hostnames are actually in.
+  const [rows, setRows] = useState<Record<string, { mode: HostMode; root: string }>>({})
+
   useEffect(() => {
     const d = staticQuery.data
     if (!d) return
@@ -93,6 +144,18 @@ export default function ProjectStaticTab() {
     setMount(d.mount)
     setIndex(d.index)
     setCacheControl(d.cache_control)
+    const next: Record<string, { mode: HostMode; root: string }> = {}
+    for (const h of d.hostnames ?? []) {
+      next[h.host] = {
+        // `configured` is the only thing that separates "following, and the
+        // project happens to be on" from "set individually to on". Reading the
+        // mode off `enabled` alone would silently convert every following host
+        // into a pinned one on the next save.
+        mode: h.configured ? (h.enabled ? 'serve' : 'off') : 'follow',
+        root: h.root || '/',
+      }
+    }
+    setRows(next)
   }, [staticQuery.data])
 
   if (!admin) {
@@ -109,7 +172,6 @@ export default function ProjectStaticTab() {
   if (staticQuery.error) return <p className="text-sm text-rose-400">{String(staticQuery.error)}</p>
 
   const hostnames = hostsQuery.data?.hostnames ?? []
-  const firstHost = hostnames[0]?.host ?? ''
   /// The gate, shown rather than merely enforced. A project with no hostname
   /// cannot serve files at all, because there is no name for a browser to ask
   /// on - so the switch is disabled and says why, instead of letting the user
@@ -120,7 +182,14 @@ export default function ProjectStaticTab() {
   const notServed = !noHostname && hostsQuery.data?.served === false
 
   const clientMountError = mountError(mount)
-  const canSave = !saving && clientMountError === null
+  /// The first per-host root that will not do, with the host it belongs to, so
+  /// the message can name it. A root error must block the save for the same
+  /// reason a mount error does: the server refuses it 422 and the whole form
+  /// then fails, including the fields that were fine.
+  const badRoot = hostnames
+    .map((h) => ({ host: h.host, why: rows[h.host]?.mode === 'follow' ? null : rootError(rows[h.host]?.root ?? '/') }))
+    .find((x) => x.why !== null)
+  const canSave = !saving && clientMountError === null && badRoot === undefined
 
   async function onSubmit(e: React.FormEvent) {
     e.preventDefault()
@@ -128,25 +197,48 @@ export default function ProjectStaticTab() {
     // Belt and braces: the submit button is already disabled on a bad mount,
     // but a form can be submitted by Enter in a text field.
     if (mountError(mount) !== null) return
+    // Only the names set INDIVIDUALLY are sent. A `follow` row is expressed by
+    // its ABSENCE from this array, which is why the array is always sent in
+    // full: present replaces the whole set, so omitting a row is how a host is
+    // returned to the project switch. Sending only the changed rows would
+    // silently clear every other host's block.
+    const perHost: ProjectStaticHost[] = hostnames
+      .filter((h) => (rows[h.host]?.mode ?? 'follow') !== 'follow')
+      .map((h) => ({
+        host: h.host,
+        enabled: rows[h.host].mode === 'serve',
+        root: (rows[h.host].root || '/').trim(),
+      }))
     const body: ProjectStaticSettings = {
       enabled,
       mount: mount.trim(),
       index: index.trim(),
       cache_control: cacheControl,
+      hostnames: perHost,
     }
     setSaving(true)
     setServerMountError(null)
     try {
       await api.updateProjectStatic(project, body)
       await qc.invalidateQueries({ queryKey: ['project-static', project] })
+      // Counted rather than named, because with per-host roots there is no
+      // single origin to quote: a message naming one hostname would be a
+      // confident wrong answer about the others.
+      const serving = hostnames.filter((h) => {
+        const m = rows[h.host]?.mode ?? 'follow'
+        return m === 'serve' || (m === 'follow' && body.enabled)
+      }).length
       toast(
-        body.enabled
-          ? `Static serving is ON. Files with a path are now public at ${servedOrigin(firstHost, body.mount)}`
-          : 'Static serving is OFF. Stored files are private again.',
+        serving === 0
+          ? 'Saved. No hostname is serving files, so stored files stay private.'
+          : serving === 1
+            ? 'Saved. 1 hostname is serving files publicly, with no key.'
+            : `Saved. ${serving} hostnames are serving files publicly, with no key.`,
         'success',
       )
     } catch (err) {
-      if (err instanceof ApiError && err.code === 'invalid_mount') {
+      if (err instanceof ApiError && (err.code === 'invalid_mount' || err.code === 'invalid_root' ||
+                                      err.code === 'unknown_hostname')) {
         setServerMountError(err.message)
       }
       toast(err instanceof ApiError ? err.message : String(err), 'error')
@@ -187,8 +279,8 @@ export default function ProjectStaticTab() {
       )}
 
       <FormRow
-        label="Serve files publicly"
-        hint="Off by default, and off is the safe state. Turning this on publishes every file carrying a path to anyone who knows the address - no key, no session, no referer check."
+        label="Serve files publicly by default"
+        hint="The default for every hostname that has no setting of its own. Off is the safe state: turning this on publishes every file carrying a path to anyone who knows the address - no key, no session, no referer check. A hostname set individually below ignores this."
         badge={enabled ? <Badge tone="amber">public</Badge> : <Badge>private</Badge>}
       >
         <div className="flex flex-col gap-2">
@@ -209,15 +301,10 @@ export default function ProjectStaticTab() {
             </p>
           )}
           {!noHostname && (
-            <p
-              className={enabled ? 'text-xs text-amber-300' : 'text-xs text-slate-500'}
-              data-testid="static-origin"
-            >
-              {enabled ? 'Will serve at ' : 'Would serve at '}
-              <code className="text-slate-100">{servedOrigin(firstHost, mount)}</code>
-              {hostnames.length > 1 && (
-                <span className="text-slate-500"> (and {hostnames.length - 1} more hostname{hostnames.length > 2 ? 's' : ''})</span>
-              )}
+            <p className="text-xs text-slate-500" data-testid="static-origin">
+              Applies to every hostname below marked <em>follows the default</em>. Each hostname's
+              own address is listed there, because with per-hostname roots there is no single
+              origin to name.
             </p>
           )}
         </div>
@@ -288,6 +375,104 @@ export default function ProjectStaticTab() {
         />
       </FormRow>
 
+      {!noHostname && (
+        <div className="flex flex-col gap-3" data-testid="static-hostnames">
+          <div>
+            <h3 className="text-sm font-medium text-slate-200">Per hostname</h3>
+            <p className="text-xs text-slate-400 mt-1">
+              Each hostname decides for itself whether it serves and which subtree is its
+              document root. The mount, index and Cache-Control above are project-wide and apply
+              to all of them, so there is exactly one place to change a cache policy.
+            </p>
+            <p className="text-xs text-slate-500 mt-1">
+              The document root is <strong>invisible in the URL</strong>: a hostname rooted at{' '}
+              <code>/sites/a</code> answers a request for <code>/</code> with the file stored at{' '}
+              <code>/sites/a/index.html</code>. That is how two hostnames serve different sites
+              out of one project. There is no master switch - a hostname set to serve does serve,
+              whatever the default above says.
+            </p>
+          </div>
+
+          {hostnames.map((h) => {
+            const row = rows[h.host] ?? { mode: 'follow' as HostMode, root: '/' }
+            const effectiveOn = row.mode === 'serve' || (row.mode === 'follow' && enabled)
+            const effectiveRoot = row.mode === 'follow' ? '/' : row.root
+            const why = row.mode === 'follow' ? null : rootError(row.root)
+            return (
+              <div
+                key={h.host}
+                className="rounded-md border border-slate-700 bg-slate-800/40 px-4 py-3 flex flex-col gap-2"
+                data-testid={`static-host-${h.host}`}
+              >
+                <div className="flex flex-wrap items-center gap-2">
+                  <code className="text-sm text-slate-100">{h.host}</code>
+                  {effectiveOn ? <Badge tone="amber">public</Badge> : <Badge>private</Badge>}
+                  {row.mode === 'follow' && <Badge>follows the default</Badge>}
+                </div>
+
+                <div className="flex flex-wrap items-center gap-3">
+                  <select
+                    value={row.mode}
+                    onChange={(e) => {
+                      const mode = e.target.value as HostMode
+                      setRows((prev) => ({ ...prev, [h.host]: { mode, root: prev[h.host]?.root ?? '/' } }))
+                      setServerMountError(null)
+                    }}
+                    className={`${controlCls} w-56`}
+                    data-testid={`static-host-mode-${h.host}`}
+                  >
+                    <option value="follow">Follows the default</option>
+                    <option value="serve">Serve files</option>
+                    <option value="off">Do not serve</option>
+                  </select>
+
+                  {/* The root input appears only when this hostname decides for
+                      itself. A root shown beside "follows the default" would
+                      imply it was being stored, and it is not: a following host
+                      has no block at all and always serves the whole tree. */}
+                  {row.mode !== 'follow' && (
+                    <input
+                      type="text"
+                      value={row.root}
+                      placeholder="/"
+                      onChange={(e) => {
+                        const root = e.target.value
+                        setRows((prev) => ({ ...prev, [h.host]: { mode: prev[h.host]?.mode ?? 'serve', root } }))
+                        setServerMountError(null)
+                      }}
+                      className={`${controlCls} w-72`}
+                      aria-label={`Document root for ${h.host}`}
+                      data-testid={`static-host-root-${h.host}`}
+                    />
+                  )}
+                </div>
+
+                {why && (
+                  <p className="text-xs text-rose-400" data-testid={`static-host-root-error-${h.host}`}>
+                    {why}
+                  </p>
+                )}
+
+                {!why && effectiveOn && (
+                  <p className="text-xs text-slate-500">
+                    <code className="text-slate-300">{servedOrigin(h.host, mount)}/</code> serves the
+                    file stored at{' '}
+                    <code className="text-slate-300">{resolvedExample(effectiveRoot, index)}</code>
+                  </p>
+                )}
+                {!why && !effectiveOn && (
+                  <p className="text-xs text-slate-500">
+                    {row.mode === 'off'
+                      ? 'Set not to serve: files stay private on this hostname even though the default above is on.'
+                      : 'Follows the default, which is off, so nothing is served on this hostname.'}
+                  </p>
+                )}
+              </div>
+            )
+          })}
+        </div>
+      )}
+
       {/* SaveButton IS the button, with type="submit" - wrapping it in another
           button nests one inside the other and only works by accident. */}
       <div className="flex items-center gap-3">

+ 48 - 0
webui/src/types/index.ts

@@ -343,6 +343,38 @@ export interface InvokeRequest {
 export interface ProjectHostname {
   host: string
   path_style: 'short' | 'full'
+  /// This hostname's own static-serving block, or absent to follow the
+  /// project's. READ ONLY here: the hostnames route refuses to write it,
+  /// because it replaces the whole list and a block sent there would be
+  /// dropped by the next unrelated edit. Written on /settings/static.
+  static?: ProjectHostStatic
+}
+
+/// One hostname's half of the static configuration.
+///
+/// Every field lives in exactly one place: `enabled` and `root` belong to a
+/// HOSTNAME, while `mount`, `index` and `cache_control` belong to the project.
+/// A present block is authoritative for its two fields and does not inherit,
+/// which is why `enabled` is required rather than optional.
+export interface ProjectHostStatic {
+  enabled: boolean
+  /// The hostname's document root: prepended to the lookup and invisible in
+  /// the URL, like nginx's `root`. '/' is the whole tree and is the default.
+  root: string
+}
+
+/// One hostname as the STATIC route reports it: the EFFECTIVE answer for that
+/// name, so a host following the project shows what it will really do rather
+/// than a blank. `configured` is what distinguishes that from a host set
+/// individually to the same values.
+export interface ProjectStaticHost {
+  host: string
+  enabled: boolean
+  root: string
+  /// GET only. A PUT sends {host, enabled, root} and nothing else, so these
+  /// two are optional rather than a second near-identical interface.
+  configured?: boolean
+  served?: boolean
 }
 
 /// GET /settings/hostnames. `served` is NOT derivable from the list: with no
@@ -371,6 +403,22 @@ export interface ProjectStaticSettings {
   index: string
   /// Sent verbatim on every served file.
   cache_control: string
+  /// PER-HOSTNAME blocks.
+  ///
+  /// On a GET this is EVERY registered hostname with its effective values. On a
+  /// PUT it is optional, and the asymmetry is load-bearing: PRESENT replaces
+  /// the whole set of per-host blocks, ABSENT leaves them alone. So a PUT
+  /// carrying only `cache_control` is not a publishing change, and an empty
+  /// array is the only way to return every name to the project's own switch.
+  hostnames?: ProjectStaticHost[]
+  /// GET only: whether the project-wide values above are STORED or are the
+  /// built-in defaults being shown.
+  configured?: boolean
+  /// GET only: SOME hostname publishes. NOT 'the project switch is on' - a
+  /// project whose own `enabled` is false can still publish one name.
+  served?: boolean
+  /// GET only.
+  has_hostname?: boolean
 }
 
 /// PUT /settings/hostnames. The body REPLACES the whole list: a partial list