# HTML cache for AI agents

Operator guide to the experimental HTML cache: report-only first, the steps to serve Markdown copies, what is stored and served, purging and counters.

Canonical URL: https://modpagespeed.com/docs/html-cache/

This page is the operator guide to the module's HTML cache in `serve-variants`
mode. `serve-cached-html` (Apache and nginx), which also answers HTML requests
from the stored page, needs the same setup steps and stores pages under the
same rules; what it adds (its scope, its age cap and its cookie policy) is in
[Serve stored pages from the module](https://modpagespeed.com/docs/agent-optimize/#serve-stored-pages-from-the-module-apache-and-nginx).
For how agent optimization works as a whole, see
[Serve Markdown to AI agents](https://modpagespeed.com/docs/agent-optimize/).

> **Experimental.** The HTML cache (`DaemonHtmlCache` and the
> `DaemonHtmlCache*` settings) is experimental: its behaviour, counters and
> decision log may change between releases.

`DaemonHtmlCache serve-variants` lets Apache, nginx and IIS keep a copy of each
HTML page they serve and answer a request that prefers `text/markdown` with a
Markdown copy of that page, at the same URL. Browsers, search engines and every
request that does not ask for Markdown keep getting the HTML page.

The HTML cache is off by default, and serving is opt-in: nothing is stored or
served unless every step in [Turn it on](https://modpagespeed.com/docs/html-cache/#turn-it-on) is done. The safe first step is
`report-only`, which only counts and logs (see [First step: report-only](https://modpagespeed.com/docs/html-cache/#first-step-report-only)
below), and `off` turns the HTML cache off entirely.

On IIS the notes in the [IIS section](https://modpagespeed.com/docs/html-cache/#iis) below apply.

## First step: report-only

`DaemonHtmlCache` is `off` by default on Apache, nginx and IIS. Set
`report-only` first to see what could be cached:

```apache
ModPagespeedDaemonHtmlCache report-only
```

```nginx
pagespeed DaemonHtmlCache report-only;
```

On IIS, in the configuration file: `pagespeed DaemonHtmlCache report-only`.

- **What it does.** With an optimizer library that publishes the HTML store
  policy (C API minor version 12 or later), it judges each HTML response the module
  rewrites (a `200` with a body, not a `HEAD`) and counts whether the policy
  would store it (`daemon_html_evaluated`, `daemon_html_would_store`,
  `daemon_html_refused_<reason>`). It never stores or serves anything, never
  changes a response or its headers, and sends nothing to the optimizer
  worker. Without such a library it does nothing at all: no
  per-request work, no counters, no log line.
- **What it costs** once turned on, on Apache, nginx and IIS with such a
  library:
  - For every request the module handles, images and stylesheets included:
    the request's `User-Agent` is classified against the built-in list of AI
    agent tokens and counted in `daemon_html_agent_class_*`; on nginx the main
    request's URL is parsed and its host checked; on Apache the
    handler, file, path info and query of the request are noted; on IIS
    the URL the request executes is read.
  - For each HTML response the module rewrites: the request's facts and the
    response's header lines are copied (as the origin sent them and as the
    server sends them; on Apache also a baseline, and a small per-response
    object is allocated), up to the first 64 KiB of the body is copied, and
    the library classifies the response. With C API minor version 15 or later the request
    policy (credentials, request headers, path) is also evaluated and the body
    is scanned for the values of listed analytics cookies the request carries.
  - Where `LogDir` is set, a decision log is written to
    `<LogDir>/daemon-html/decisions-YYYY-MM-DD.jsonl` (UTC date), at most 100
    lines per second per server process and about 50 MB per day, and day
    files are kept for 14 days, so at most about 700 MB per `LogDir`.
    Turning the mode off stops new lines but leaves the existing day files
    in place. Without `LogDir` the server logs a warning that the decision
    log is off.
  - The daily cap is shared by every server process and virtual host that
    writes to that `LogDir`. A burst of traffic can reach it early in the
    day, and that day's later decisions are then dropped: disk use stays
    bounded, and the drops (like those over the per-second limit) count in
    `daemon_html_log_dropped`.
  - Each decision line records the request's host and path. The path is cut
    at the query string, a fragment or `;` parameters, which are never
    written, but it is still a record of what was requested: treat the
    decision log like an access log.
- **Serving** (`serve-variants`, `serve-cached-html`) needs an optimizer
  library with C API minor version 15 or later; see [What you need](https://modpagespeed.com/docs/html-cache/#what-you-need) below.

## What you need

The module alone does not produce the Markdown copy. A worker does, and the
module and the worker have to agree:

- The optimizer library installed with the module must publish C API minor version 15 or
  later, on every server. `pagespeed-optimizer` 2.11.0 is the first release
  whose library publishes C API minor versions 15 and 16. Each stored page is bound to the target the request
  ran (on Apache the handler, file, path info and query; on IIS the URL after
  URL Rewrite) and carries the record of the policy it was stored under, which
  needs it. With an older library the module logs one warning and stays in
  `report-only`: nothing is stored or served, Markdown copies included.
- The optimizer worker must run with `--html-mode markdown-static` (or
  `markdown-rendered`) and `--agent-optimize`. `html_mode` is a setting of the
  whole worker, not of one site. The worker derives the copy from the stored
  page alone: no browser runs and no request leaves the worker.
  The Docker images set `--agent-optimize` with `PAGESPEED_AGENT_OPTIMIZE=true`
  but have no variable for the HTML mode, and they do not pass arguments
  through. Set the mode with the `html_mode` key in `pagespeed.json`, which the
  worker reads at start from the directory that holds its cache volume (the
  data directory, `/data` by default, in the images), or with
  `PATCH /v1/config` on the worker's management API (enabled with
  `PAGESPEED_API_PORT` or `PAGESPEED_API_SOCKET` in the images).
- The module needs `AgentOptimize on` and `DaemonHtmlCache serve-variants`.
- A `LogDir` is needed for the decision log (below).
- nginx must be 1.13.10 or later.

## Turn it on

Do the steps in this order.

1. Install the optimizer and restart it before you reload the web server. A
   worker from before 2.11.0 refuses the module's notifications.
2. Start the worker with `--html-mode markdown-static` and `--agent-optimize`
   (or set `html_mode` as described above).
3. Set `report-only` first, with `AgentOptimize on`, and let traffic run:

   Apache. Set both directives in the `VirtualHost` (or at server level, which
   virtual hosts inherit). Inside `<Location>`, `<Directory>` or `.htaccess`,
   `AgentOptimize` does not turn serving on, and `AgentOptimize off` there does
   not stop it. To keep a path out, turn PageSpeed off there
   (`ModPagespeed off`) or use `ModPagespeedDisallow`:

   ```apache
   ModPagespeedAgentOptimize on
   ModPagespeedDaemonHtmlCache report-only
   ```

   nginx, in the `server` block (or `http`):

   ```nginx
   pagespeed AgentOptimize on;
   pagespeed DaemonHtmlCache report-only;
   ```

   In `report-only` nothing a client receives changes. Each HTML response is
   judged and counted: `daemon_html_would_store` against
   `daemon_html_refused_<reason>`, and the decision log in
   `<LogDir>/daemon-html`
   gives the reason for each page. Read them before going on. If most of your
   pages are refused for `no_lifetime`, `vary`, `headers` or `private`, they
   would gain nothing from `serve-variants`.
4. Change the value to `serve-variants` and reload. The log then says that the
   optimizer library and worker allow serving. If they do not, the module logs
   why (for example, that the worker's `html_mode` is not a Markdown mode, or
   that the optimizer library is older than C API minor version 15) each time that state
   changes, and keeps running as `report-only`;
   `daemon_html_serve_unavailable` counts the HTML responses seen in that
   state.
5. Check with a `GET` that prefers Markdown:

   ```sh
   curl -s -o /dev/null -D - -H 'Accept: text/markdown' https://example.com/page
   ```

   The first `GET` for a page gets HTML: it stores the page, and the worker then
   derives the copy. Repeat the request after a few seconds; it then gets
   `Content-Type: text/markdown`. A `HEAD` request never stores a page, so do
   not use `curl -I` for this check.

`DaemonHtmlMaxBytes` (default 5 MiB) is the largest HTML body that is stored.
To switch back, set `DaemonHtmlCache report-only` and reload, or `off` (the
default) to stop the report too; either is the kill switch.

## What is stored and what is served

A page is stored only when all of these hold:

- It was served for one of the virtual host's own names (Apache `ServerName` or
  an exact `ServerAlias`; nginx an exact `server_name`). Wildcard aliases and
  requests that reach the default host are not stored.
- The origin gave it an explicit lifetime (`max-age`, `s-maxage` or
  `Expires`). A page without one, and a `no-cache` page, is not stored.
  On nginx, an `add_header Cache-Control` beside the origin's own line leaves
  the page with no lifetime (see [nginx](https://modpagespeed.com/docs/html-cache/#nginx) below).
- Its headers allow a shared cache to keep it: no `Set-Cookie`,
  `Cache-Control: private` or `no-store`, and no `Vary` naming anything other
  than `Accept-Encoding`.
- The response as your server configuration sends it allows it too. Headers
  added by `Header set` and `mod_expires` (Apache) or `add_header` and `expires`
  (nginx) count: a header that refuses caching refuses the store, and where the
  configuration replaces the lifetime the shorter of the two applies. Those
  headers do not become part of the stored copy.
- The request was answered on its first pass under the URL exactly as sent.
  A request the server and the module read differently (merged slashes,
  percent-escaped paths, dot segments, a request line naming another host than
  `Host`) is left to the server. A page a front controller answers after one
  internal redirect (WordPress, Drupal or Laravel pretty URLs sent to
  `index.php`, or a directory URL served by its index file) is stored and
  served under the URL the client asked for, the HTML page and its Markdown
  copy, bound to the target the server ran. Other internal redirects are
  neither stored nor served; see [Apache](https://modpagespeed.com/docs/html-cache/#apache) and [nginx](https://modpagespeed.com/docs/html-cache/#nginx) below.

A page whose response carries a `CDN-Cache-Control` or `Surrogate-Control`
header added by your server configuration is refused, so a site that adds one
to every HTML response gets no HTML cache.

The Markdown copy is served only for a `GET` or `HEAD` request that prefers it
(`text/markdown` listed with a q-value at least that of `text/html`). A request
with credentials (`Authorization`), `Range`, `If-Range`, `Origin`, or cookies
other than the listed analytics cookies (`DaemonHtmlCacheIgnoreCookies`,
`DaemonHtmlCacheIgnoreCookie`) gets the HTML page. Access, authentication and authorization run before any Markdown answer.
A location where PageSpeed is off never serves Markdown, and Markdown is served
with in-place optimization off.

### The Markdown response

The response carries exactly: `Content-Type: text/markdown; charset=utf-8`,
`Content-Length`, `Cache-Control: private`, one `Vary` line (`Accept`, plus any
`Vary` tokens the origin sent), `X-Robots-Tag: noindex`, `Age` and a weak
`ETag`, besides the server's own transport lines (`Date`, `Server` and the
like), and `Content-Encoding` when a compressed copy is sent (below). A
matching `If-None-Match` gets a `304` with `ETag`, `Cache-Control` and `Vary`.

Consequences to plan for:

- Headers your configuration adds to every response, including
  `Strict-Transport-Security` and `X-Content-Type-Options`, are not applied to
  the Markdown copy. Set them at a stage in front of the server.
- With an optimizer library that publishes C API minor version 16 the optimizer stores a
  brotli and a gzip copy of each Markdown copy beside the plain one, and a
  request is answered with the one its `Accept-Encoding` prefers (q-values
  honoured; a coding the request ranks below the plain copy is not used). The
  answer then carries `Content-Encoding: br` or `gzip`, the coded length and an
  entity tag of that coding, so a `304` is given only for the tag of the coding
  asked for. The copies are compressed once by the optimizer, never per
  request, and the server's own compression never compresses them again. A
  request that accepts no coding the copy is stored in (`identity;q=0` with no
  coded copy ready) goes to the origin. A page stored before the optimizer
  wrote coded copies gets them after its first Markdown request (asked once
  per page per server process). With an older library the copy is never
  compressed.
- Every Markdown answer's `Vary` line lists `Accept-Encoding` after `Accept`
  when the library publishes C API minor version 16, the plain copy's too.
- With `AgentOptimize on` and `serve-variants`, every rewritten HTML response
  carries `Vary: Accept`, on Apache and on nginx. An HTML `304` does not, and on
  Apache neither does an HTML `HEAD` answer; a cache keeps the `Vary` of the
  `200`.
- `Cache-Control: private` keeps the copy out of shared caches, including CDNs
  that ignore `Vary`. Behind a CDN, `Age` can cost extra cache misses.
- A script's request is never stored and never answered with the Markdown
  copy: one whose `X-Requested-With` contains `XMLHttpRequest` anywhere
  (any case, also in a value joined from repeated lines), or that carries a
  non-empty `X-MicrosoftAjax` or `X-Prototype-Version`. It counts in
  `daemon_html_refused_request_header` (see [Counters](https://modpagespeed.com/docs/html-cache/#counters)).
- With optimizer C API minor version 15, `report-only` applies the whole request policy the same way, so its
  numbers say what serving would keep: a request with only listed analytics
  cookies counts as one that would be stored, unless the page repeats the
  value of one of those cookies (counted refused, in
  `daemon_html_refused_cookie_echo`, as a store refuses it), and one refused
  for a request header, its path or a mismatched `X-Forwarded-Proto` counts
  as evaluated and refused for that reason. A request with more than 32
  listed cookie values, or with values more than 4 KiB long together
  (counting their percent-decoded forms), is treated as carrying a cookie
  outside the ignore list.

### Apache

- A page a front controller's `RewriteRule` (in `.htaccess` or a `<Directory>`
  block) sends to a local script, such as the stock WordPress rules, is stored
  and served under the URL the client asked for. It is bound to the handler,
  file, path info and query the redirected request ran, and answered only after
  that request's access, authentication and authorization checks. `DirectoryIndex`
  works too: `/` served as `index.html` is stored and served.
- A request that goes through more than one internal redirect, an
  `ErrorDocument`, or a redirect another handler made (an `Action` handler, a CGI
  script's local `Location`) is neither stored nor served. Each is counted once
  in `daemon_html_internal_refused` when its response would otherwise be stored,
  with the cause in the decision log.
- A decoded path containing `?`, `#`, a space, a control byte or DEL is neither
  stored nor served.
- A compressed copy is written as stored and never encoded again. A stage
  outside the content filters that encodes it a second time is kept (both
  codings are named, so the body still decodes) and counted in
  `daemon_markdown_transport_conflict`, unless it applies the same coding the
  copy is in, which is not detected.
- Content filters (every output filter ahead of the protocol stage) do not run
  on a Markdown answer, so
  `mod_security` response-body scanning and `mod_substitute` do not see it.
  Set security headers at a front stage.

### nginx

- A page behind a front controller (`try_files $uri $uri/ /index.php?$args;`,
  or the `index` directive for a directory URL) is stored and served under the
  client's URL, the HTML page and its Markdown copy. It is bound to the URI the
  redirect sends the request to, its arguments and the file that URI maps to,
  and answered in the target's location after its access phase (`allow`/`deny`,
  `auth_basic`, `auth_request`).
- Only one redirect from the client's URL qualifies. `error_page` (except
  `error_page 404 = /index.php` with `recursive_error_pages on`, which nginx makes
  indistinguishable from `try_files`),
  `X-Accel-Redirect`, named locations, a `rewrite` ahead of the redirect and a
  second redirect are neither stored nor served; each is counted once in
  `daemon_html_internal_refused`, with the cause in the decision log, when its
  response would otherwise be stored.
- A static file nginx serves without an upstream `Cache-Control` has no
  lifetime of its own, because `expires` is applied after the store decision.
  Such pages are never served as Markdown on nginx.
- `add_header Cache-Control ...` adds a second `Cache-Control` line beside the
  origin's. Two lines with different `max-age` values conflict, so the page
  keeps no lifetime and is never served as Markdown. Set the lifetime at the
  origin and do not add a `Cache-Control` line with `add_header`.
- Body filters still run on a Markdown answer. When one would rewrite it
  (`sub_filter`, `ssi`, `addition` or another filter that clears the length
  for `text/markdown`), a request that prefers a compressed copy gets the plain
  copy instead, with the plain copy's entity tag, so the filter sees text; it
  counts `daemon_markdown_coded_fallback`. That happens also for a request
  that refused the uncompressed form (`identity;q=0`), and such a client gets
  a full `200` each time, as its `If-None-Match` names the compressed copy's
  tag. `charset` recoding never applies to
  a compressed copy (nginx skips an encoded response). With `gunzip on` the
  gzip copy reaches a client that accepts gzip unchanged.
- A `proxy_hide_header` does not hide a `Set-Cookie`, `Cache-Control`, `Vary`
  or `Pragma` from the store decision.

## Purging

A URL purge (the purge method or `?purge=`) removes the stored page and its
copy; one that cannot remove it reports a failure. The URL is matched with its
host in lowercase and a default port removed, but a purge for a different
scheme does not match. A global purge, from the admin page or a touch of
`cache.flush` (read while `EnableCachePurge` is off), fences everything stored
before it.

- A purge takes effect in other server processes within one poll interval
  (`CacheFlushPollIntervalSec`, default 5 seconds).
- A global purge is kept in a per-site file beside the cache volume. If that
  file cannot be read, the whole site is fenced until it can.
- After touching `cache.flush`, wait one poll interval
  (`CacheFlushPollIntervalSec`) before wiping the file cache. A wipe before any
  server process has seen the touch loses that purge.

## Limits

- The Markdown copy is extracted from the stored HTML without running a browser
  (`markdown-static` style). Text hidden only by a CSS class or an external
  stylesheet stays in the copy.
- A page whose Markdown body is too small to be useful gets no copy, and agents
  get the page itself.
- If your origin refuses caching for some requests based on a request header
  (for example `Cache-Control: private` for one `User-Agent`), such a request
  removes the stored copy, and agents get HTML until the page is stored again.
  Mark such pages `private` for every request, or let them vary only on
  `Accept-Encoding`.
- One entry is stored per site path, whatever port it is requested on.
- The decision log is a file under `<LogDir>/daemon-html`; the admin console's
  HTML cache panel shows the mode, the counters and the reasons serving is not
  active, but does not show the log.

## Counters

All are on the statistics page and in the admin console's HTML cache panel.

A request the request policy refuses (for its credentials, cookies, a request
header or its path) is counted once when its response would be stored, and once
more at each lookup the cache makes for it: for a Markdown request, and in
`serve-cached-html` for an HTML request the server answers from the stored page.
Only the count at the store is part of `daemon_html_evaluated` and
`daemon_html_refused`.

| Counter | Meaning |
|---|---|
| `daemon_html_evaluated`, `daemon_html_would_store`, `daemon_html_refused` | HTML responses judged, ones the policy would store, and ones it refused, in every mode. |
| `daemon_html_refused_<reason>` | Refusals by reason, for example `no_lifetime`, `vary`, `headers`, `private` or `cookie_echo`. |
| `daemon_html_refused_request_header` | Requests refused for a request header: a script's request, or (C API minor version 15) a header the cache key does not contain. |
| `daemon_html_refused_auth`, `daemon_html_refused_cookie_request`, `daemon_html_refused_path` | Requests refused for credentials, for cookies outside the ignore list, or for their path (C API minor version 15). |
| `daemon_html_refused_url_disagree`, `daemon_html_refused_budget` | Requests the module itself would not record: a URL the server and the module read differently, or a body over the budget. Not part of `daemon_html_evaluated` or `daemon_html_refused`. |
| `daemon_html_internal_refused` | Responses after an internal redirect that does not qualify (more than one hop, an error page other than nginx's `error_page 404 = /index.php` with `recursive_error_pages on`, `X-Accel-Redirect`, a named location, a `rewrite` ahead of the redirect, a redirect another handler made). The cause is in the decision log. |
| `daemon_html_internal_stored`, `daemon_html_internal_served_html`, `daemon_markdown_internal_served` | Front-controller pages stored, answered as HTML from the stored page, and answered with their Markdown copy. |
| `daemon_html_stored`, `daemon_html_removed`, `daemon_html_removed_on_refusal` | Entries written, entries removed, and entries removed because a later response for the URL refused caching. |
| `daemon_html_serve_unavailable` | HTML responses seen while the optimizer library or worker does not allow serving. |
| `daemon_html_notify_sent`, `daemon_html_notify_limited` | Requests to the worker to derive a Markdown copy, and ones skipped by the rate limit. |
| `daemon_markdown_served`, `daemon_markdown_not_modified` | Markdown `200` and `304` answers. |
| `daemon_markdown_served_br`, `daemon_markdown_served_gzip`, `daemon_markdown_served_identity` | Markdown `200` answers by the coding sent (C API minor version 16). |
| `daemon_markdown_encoded_copy_missing`, `daemon_markdown_encoded_copy_unbound`, `daemon_markdown_compress_demand_sent` | A compressed copy a request preferred that was not stored yet, or was made from an earlier copy; and the requests to the optimizer to write one. |
| `daemon_markdown_coded_fallback` | Compressed answers sent as the plain copy because a body filter would have rewritten them (nginx). |
| `daemon_markdown_fallthrough_<reason>` | Requests that preferred Markdown and got HTML, by reason, for example `absent`, `stale`, `withheld`, `url_disagree`, `request_header`, `cookie_request`, `range` or `no_acceptable_encoding`. |
| `daemon_html_sidecar_write_failed`, `daemon_html_epoch_write_failed`, `daemon_html_purge_remove_failed` | Write and purge failures: investigate when they grow. |
| `daemon_markdown_served_without_preference`, `daemon_markdown_transport_conflict` | Should stay 0. |

## IIS

`DaemonHtmlCache serve-variants` serves Markdown copies on IIS as on Apache and
nginx, with these differences:

- A page is stored and served only for a host name one of the site's bindings
  names. A binding with an empty host name (`*:80:` or an address only) vouches
  for no name.
- Only the plain spelling of a URL path is stored or served: lowercase ASCII,
  without percent-escapes, merged or doubled slashes, dot segments, 8.3 short
  names, a trailing dot, `;` parameters, `::$DATA` or path info after the file.
  A site whose URLs carry capitals or non-ASCII characters gets no Markdown copy
  for them.
- The Markdown answer is sent by the `PageSpeedFinalView` module entry; see the
  [2.11.0 release notes](https://modpagespeed.com/docs/release-notes-2-11/#v2-11-0) for that entry.

The compressed copies are served on IIS with the same guarantees as on Apache
and nginx: the copy the request's `Accept-Encoding` prefers, with its own
`Content-Encoding`, length and entity tag, `Accept-Encoding` in `Vary`, and
never compressed again by IIS dynamic compression. A `Range` or `If-Range`
request is answered by IIS itself, never from a copy, and one that asks for
Markdown counts `daemon_markdown_fallthrough_range` as on the other servers.
With an optimizer library that publishes C API minor version 15, a request rewritten by URL
Rewrite carries `X-Original-URL` with the request target as the client sent it;
the HTML cache accepts it because it equals the target the page is keyed on. A
request whose `X-Original-URL` differs from its target is neither stored nor
answered, and the site logs one warning saying so.
