HTML cache for AI agents
Last updated Edit this page View as Markdown
Operator guide to the experimental HTML cache: report-only first, the steps to serve Markdown copies, what is stored and served, purging and counters.
On this page
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.
For how agent optimization works as a whole, see
Serve Markdown to AI agents.
Experimental. The HTML cache (
DaemonHtmlCacheand theDaemonHtmlCache*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 is done. The safe first step is
report-only, which only counts and logs (see First step: report-only
below), and off turns the HTML cache off entirely.
On IIS the notes in the IIS section 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:
ModPagespeedDaemonHtmlCache report-only
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
200with a body, not aHEAD) 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-Agentis classified against the built-in list of AI agent tokens and counted indaemon_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
LogDiris 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 perLogDir. Turning the mode off stops new lines but leaves the existing day files in place. WithoutLogDirthe 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 indaemon_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.
- For every request the module handles, images and stylesheets included:
the request’s
- Serving (
serve-variants,serve-cached-html) needs an optimizer library with C API minor version 15 or later; see 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-optimizer2.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 inreport-only: nothing is stored or served, Markdown copies included. - The optimizer worker must run with
--html-mode markdown-static(ormarkdown-rendered) and--agent-optimize.html_modeis 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-optimizewithPAGESPEED_AGENT_OPTIMIZE=truebut have no variable for the HTML mode, and they do not pass arguments through. Set the mode with thehtml_modekey inpagespeed.json, which the worker reads at start from the directory that holds its cache volume (the data directory,/databy default, in the images), or withPATCH /v1/configon the worker’s management API (enabled withPAGESPEED_API_PORTorPAGESPEED_API_SOCKETin the images). - The module needs
AgentOptimize onandDaemonHtmlCache serve-variants. - A
LogDiris needed for the decision log (below). - nginx must be 1.13.10 or later.
Turn it on
Do the steps in this order.
-
Install the optimizer and restart it before you reload the web server. A worker from before 2.11.0 refuses the module’s notifications.
-
Start the worker with
--html-mode markdown-staticand--agent-optimize(or sethtml_modeas described above). -
Set
report-onlyfirst, withAgentOptimize 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,AgentOptimizedoes not turn serving on, andAgentOptimize offthere does not stop it. To keep a path out, turn PageSpeed off there (ModPagespeed off) or useModPagespeedDisallow:ModPagespeedAgentOptimize on ModPagespeedDaemonHtmlCache report-onlynginx, in the
serverblock (orhttp):pagespeed AgentOptimize on; pagespeed DaemonHtmlCache report-only;In
report-onlynothing a client receives changes. Each HTML response is judged and counted:daemon_html_would_storeagainstdaemon_html_refused_<reason>, and the decision log in<LogDir>/daemon-htmlgives the reason for each page. Read them before going on. If most of your pages are refused forno_lifetime,vary,headersorprivate, they would gain nothing fromserve-variants. -
Change the value to
serve-variantsand 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’shtml_modeis 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 asreport-only;daemon_html_serve_unavailablecounts the HTML responses seen in that state. -
Check with a
GETthat prefers Markdown:curl -s -o /dev/null -D - -H 'Accept: text/markdown' https://example.com/pageThe first
GETfor a page gets HTML: it stores the page, and the worker then derives the copy. Repeat the request after a few seconds; it then getsContent-Type: text/markdown. AHEADrequest never stores a page, so do not usecurl -Ifor 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
ServerNameor an exactServerAlias; nginx an exactserver_name). Wildcard aliases and requests that reach the default host are not stored. - The origin gave it an explicit lifetime (
max-age,s-maxageorExpires). A page without one, and ano-cachepage, is not stored. On nginx, anadd_header Cache-Controlbeside the origin’s own line leaves the page with no lifetime (see nginx below). - Its headers allow a shared cache to keep it: no
Set-Cookie,Cache-Control: privateorno-store, and noVarynaming anything other thanAccept-Encoding. - The response as your server configuration sends it allows it too. Headers
added by
Header setandmod_expires(Apache) oradd_headerandexpires(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 toindex.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 and 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-SecurityandX-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-Encodingprefers (q-values honoured; a coding the request ranks below the plain copy is not used). The answer then carriesContent-Encoding: brorgzip, the coded length and an entity tag of that coding, so a304is 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=0with 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
Varyline listsAccept-EncodingafterAcceptwhen the library publishes C API minor version 16, the plain copy’s too. - With
AgentOptimize onandserve-variants, every rewritten HTML response carriesVary: Accept, on Apache and on nginx. An HTML304does not, and on Apache neither does an HTMLHEADanswer; a cache keeps theVaryof the200. Cache-Control: privatekeeps the copy out of shared caches, including CDNs that ignoreVary. Behind a CDN,Agecan cost extra cache misses.- A script’s request is never stored and never answered with the Markdown
copy: one whose
X-Requested-WithcontainsXMLHttpRequestanywhere (any case, also in a value joined from repeated lines), or that carries a non-emptyX-MicrosoftAjaxorX-Prototype-Version. It counts indaemon_html_refused_request_header(see Counters). - With optimizer C API minor version 15,
report-onlyapplies 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, indaemon_html_refused_cookie_echo, as a store refuses it), and one refused for a request header, its path or a mismatchedX-Forwarded-Protocounts 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.htaccessor 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.DirectoryIndexworks too:/served asindex.htmlis stored and served. - A request that goes through more than one internal redirect, an
ErrorDocument, or a redirect another handler made (anActionhandler, a CGI script’s localLocation) is neither stored nor served. Each is counted once indaemon_html_internal_refusedwhen 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_securityresponse-body scanning andmod_substitutedo 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 theindexdirective 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(excepterror_page 404 = /index.phpwithrecursive_error_pages on, which nginx makes indistinguishable fromtry_files),X-Accel-Redirect, named locations, arewriteahead of the redirect and a second redirect are neither stored nor served; each is counted once indaemon_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-Controlhas no lifetime of its own, becauseexpiresis applied after the store decision. Such pages are never served as Markdown on nginx. add_header Cache-Control ...adds a secondCache-Controlline beside the origin’s. Two lines with differentmax-agevalues conflict, so the page keeps no lifetime and is never served as Markdown. Set the lifetime at the origin and do not add aCache-Controlline withadd_header.- Body filters still run on a Markdown answer. When one would rewrite it
(
sub_filter,ssi,additionor another filter that clears the length fortext/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 countsdaemon_markdown_coded_fallback. That happens also for a request that refused the uncompressed form (identity;q=0), and such a client gets a full200each time, as itsIf-None-Matchnames the compressed copy’s tag.charsetrecoding never applies to a compressed copy (nginx skips an encoded response). Withgunzip onthe gzip copy reaches a client that accepts gzip unchanged. - A
proxy_hide_headerdoes not hide aSet-Cookie,Cache-Control,VaryorPragmafrom 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-staticstyle). 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: privatefor oneUser-Agent), such a request removes the stored copy, and agents get HTML until the page is stored again. Mark such pagesprivatefor every request, or let them vary only onAccept-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,::$DATAor 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
PageSpeedFinalViewmodule entry; see the 2.11.0 release notes 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.