Search by

parallelogram / craft-cache

peptolab

Full-page static caching for Craft CMS: HTML files served by nginx, purged by the cache tags each page actually used.

Package info

github.com/parallelogram-dev/parallelogram-craft-cache

Documentation

Type:craft-plugin

pkg:composer/parallelogram/craft-cache

Statistics

Installs: 12

Dependents: 0

Suggesters: 1

Stars: 0

Open Issues: 0

v1.0.0-rc2 2026-12-03 23:59 UTC

This package is auto-updated.

Last update: 2026-12-04 00:00:32 UTC


README

Full-page static caching for Craft CMS 5. Each page is stored as a plain HTML file that nginx serves without starting PHP, and is deleted the moment anything it used changes.

Status: 0.1.x, in an extended pilot. It covers storing, tagging and purging pages, the bypass cookie, the nginx include, warming, the dynamic-content endpoint, the sweep command, diagnostics and Cloudflare edge caching.

Requirements

  • PHP 8.3 or later
  • Craft CMS 5.6 or later
  • nginx, to serve cached pages without PHP. Without it, PHP still serves them, but it has to boot Craft to do so.

How it works

  1. Capture. When a front-end page renders, the plugin records every cache tag the page touched. Craft supplies these: the element the URL matched, every element query, every {% cache %} block replayed from cache, and anything other Parallelogram plugins (Nav, SEO, Images) add through craft-kit. A successful HTML response is then written to the cache folder, and the page and its tags go into an index table.
  2. Serve. nginx tries the cached file before passing the request to PHP. PHP serves the files nginx can't find itself, such as pages with an allowlisted query string.
  3. Purge. Saving an element raises Craft's own tag invalidation. The plugin deletes the files of every page carrying any of those tags, straight away, so the next visitor gets a fresh render.

What gets cached

Only front-end GET requests that return 200 with HTML. None of these are ever cached:

  • POST requests
  • the control panel and action requests
  • previews and token requests
  • visitors carrying the bypass cookie
  • an entry's page asked for with different letter case from its URI, such as /NEWS/p2 for news: Craft still renders it, but only the entry's own spelling is stored, so scanners trying every spelling can't fill the cache

Query strings

Query string Result
None, or only ignored parameters (utm_*, gclid, fbclid by default) The page's own file is served.
Only allowlisted parameters (none by default; the pageTrigger parameter when Craft pages by query string, such as ?page) Each combination gets its own file, which PHP serves.
Anything else Not cached; Craft renders it every time.

Which pages a save purges

Purges use Craft's own tags, so they cover what Craft's {% cache %} tag would.

What happens What's purged
An entry is saved Pages that showed it (element::{id}), plus listing pages whose queries named its section or entry type (element::craft\elements\Entry::section:{id}), so a new product appears on its listing page.
A global set is saved Every page.
A plugin invalidates p::all Every page.
A plugin invalidates p::site:{id} Every page on that site.
A plugin invalidates p::nav:main and similar Pages that showed that menu, and the like.

Craft tags a query that names no section, entry type or field with element::craft\elements\Entry::*, which every entry save invalidates. A relation field's query (entry.relatedProjects.all()) is one of those, so on its own it would make a page purge whenever any entry is saved. While caching is on, the plugin tags a relation field's query with its source element instead (element::{id}): its results only change when that element is saved with different relations, and the related elements a template reads are tagged one by one already. This also applies to {% cache %} blocks and other plugins' tagged caches rendered on the same request.

Other queries without a section or type, such as craft.entries.all() or craft.entries.relatedTo(entry), keep the broad tag, since any new entry could appear in them. Give listings a section() or type() to keep their purges narrow. A relation field read only through .count() or .exists(), without showing the related elements, isn't purged when one of them is disabled or deleted.

After each purge the plugin fires Plugin::EVENT_AFTER_PURGE with a PagesPurgedEvent listing the URLs that went, so they can be warmed again.

Files

Pages are written under {web root}/cache/p-cache/{scheme}/{host}/{path}/:

  • index.html holds the page.
  • index~{sha1 of the query string}.html holds each allowlisted query variant.

The host carries any port other than 80 or 443 that the visitor's Host header names (example.test_8080); the port the server listens on behind a proxy doesn't count. PHP and the nginx include read it the same way. The scheme follows Craft, so X-Forwarded-Proto: https from Cloudflare counts. A plain-HTTP request to the origin therefore can't fill the cache with http:// URLs for HTTPS visitors.

Each file ends with an HTML comment carrying the build stamp:

<!-- Cached by Parallelogram Cache, build 2.3.7 -->

The stamp is the VERSION environment variable, or another variable named in the settings. When that's empty, it's the time project config last changed. PHP never serves a file from an earlier build.

nginx

Print the include for your site's server block:

php craft p-cache/nginx

The default include sets $cache_path, which a shared Craft include serves first, such as:

location / {
    try_files $cache_path $uri $uri/ /index.php?$query_string;
}

This is how the Blitz-era craftcms.conf on Parallelogram's servers already works. Include the generated file in the site's server {} block after the shared include. It replaces Blitz's $cache_path for that site only.

For a site without a shared include, print a standalone version with its own location /:

php craft p-cache/nginx --standalone

Pages nginx sends from the cache can carry an X-P-Cache: hit (nginx) header. nginx only knows which file try_files chose once it's sending the response, so the header's value comes from a map in the http block. Print it with:

php craft p-cache/nginx --http
map $uri $p_cache_hit {
    volatile;
    "~^/cache/p\-cache/" "hit (nginx)";
    default "";
}

The same output also holds a second map, $p_cache_include, which is 1 for a site that has the include and empty for any other. Pass it to PHP from the PHP location, for example in the shared php-fpm.conf:

fastcgi_param P_CACHE_INCLUDE $p_cache_include;

The control panel reads it from the request it is already serving, so its "nginx include" check needs no extra request and works behind a CDN. Without the line it says it can't tell and shows what to add.

Install it once per server, outside every server {} block (for example as /etc/nginx/conf.d/p-cache.conf), however many sites use it. Defining the map twice is an error. Sites with different cache folders need one line each in the same map.

Then add the header once, where it applies to every site:

  • Shared include: put add_header X-P-Cache $p_cache_hit; at server level in the shared include (e.g. craftcms.conf). Sites that don't use Parallelogram Cache get an empty value, so nginx sends no header for them. The generated site include doesn't add it, so there's only ever one.
  • Standalone: the generated include adds it itself, before its location /.

Either way the add_header sits at server level, so a location that serves cached pages must not have add_header lines of its own, or nginx drops the server-level ones there. Without the map, any include that names $p_cache_hit fails nginx -t with an unknown variable.

nginx serves a cached page only when all of these are true:

  • the method is GET or HEAD
  • the query string is empty, or holds only ignored parameters
  • the visitor has no bypass cookie

Everything else falls through to PHP, which applies the same rules plus the ones nginx can't check, such as the allowlisted variants and the build stamp.

Regenerate the include whenever the cache folder or the ignored parameters change.

The X-P-Cache header

Every cacheable page says how it was answered:

Value Meaning
hit (nginx) nginx sent the cached file without PHP.
hit (php) PHP sent the cached file: an allowlisted query variant, or the nginx include isn't installed.
miss The page was rendered and has just been cached.
bypass The page could have come from the cache, but the visitor has the bypass cookie.

Pages that can't be cached at all (previews, actions, other methods, unknown query strings) carry no header.

Logged-in visitors

Logging in sets a p-cache-bypass cookie, and logging out removes it. While it's present, nginx and the plugin skip the cache entirely, so logged-in visitors never see a cached page or leave one behind. Control panel logins set it too, since the same session is logged in on the front end.

Deploying

Run this as a deploy step:

php craft p-cache/deploy

It purges everything when the build stamp has changed since the last deploy, then records the new stamp and queues warming the cache again. --force purges whatever the stamp says, and --no-warm skips the warm.

Console commands and the queue only know the web root when CRAFT_WEB_ROOT is set in .env. Without it, the plugin assumes @root/web.

The sweep

Add the sweep to cron, every few minutes:

*/5 * * * * cd /path/to/site && php craft p-cache/sweep

Each run:

  • Scheduled entries. Entries whose post date or expiry date passed since the last sweep have their caches invalidated, as a save would. That purges their pages and the listings showing them. The first sweep looks back to when the oldest page still cached was rendered, since anything earlier was already reflected in it.
  • Old pages. Pages older than maxAge days are deleted, and warmed again like any other purge.
  • Orphans, at most once an hour. Index rows whose file has gone are dropped, files the index doesn't list are deleted (left behind when a site is deleted, or when a purge failed), and temporary files from writes that never finished are removed after an hour.

The sweep records when it ran, for the diagnostics page.

Pruning

php craft p-cache/prune

Deletes stored pages that wouldn't be stored today: a query string with parameters that are neither allowlisted nor ignored, or an entry's page stored under a spelling that differs in letter case from its URI. Pruned pages aren't warmed again. Run it after narrowing queryParams; the 0.1.5 update runs it once.

Diagnostics

Utilities → Cache diagnostics (admins only) checks:

  • Cache folder: caching is on and PHP can write the folder.
  • Build stamp: p-cache/deploy has run for this build, and none of the 50 oldest cached files carries another build's stamp. nginx can't read stamps, so it serves an earlier build's pages until the deploy command purges them.
  • Cached pages: how many per site, and whether any are older than the max age (the sweep should have deleted them).
  • Sweep: it ran in the last 30 minutes.
  • Re-warming: no purged URL has waited more than ten minutes past the refresh delay, which would mean nothing is running Craft's queue.
  • Pages without element tags: pages that recorded no element while rendering. Saving an entry never purges them; only global changes, deploys and the max age do. That's right for pages without CMS content, but on other pages it usually means something cached its output where Craft couldn't see, such as a cache built without element tags or content loaded outside an element query. Craft's own {% cache %} blocks replay their tags and are fine. The check can't see inside other caches, so it lists up to five such URLs to look at.
  • Serving: it requests the most recently cached URL from the server, as a visitor and again with the bypass cookie, and reads the X-P-Cache header. It reports whether nginx served it, PHP served it (the include isn't installed), it came from the cache without the header (the map is missing), or something else answered. A visitor with the bypass cookie must not get a cached page.

The page also shows the bypass cookie and the nginx include and map to copy.

Warming

Pages are warmed by Craft itself, without crawling the site over HTTP. Each page is rendered in its own short-lived PHP process that boots the site's web application for a GET request to the URL, exactly as a visitor's request through the web server would. The plugin then caches it the usual way, with the same tags. Craft can only handle a web request properly inside its web application, which a queue worker isn't, and one process can only run one web application, hence a process per page.

  • After a change: the purged pages' files are deleted straight away, so the next visitor gets a fresh render. Their URLs go on a waiting list, and a refresh job warms them after Refresh delay seconds (10 by default). A burst of saves adds to the same list and is warmed by one job: only the first purge since the last job started queues a new one. Each job warms up to Pages per warming job URLs and queues another while URLs are still waiting.
  • Everything: php craft p-cache/warm renders every URL registered URL providers list, such as Parallelogram SEO's sitemap. Without a provider it uses each site's live entries and categories that have URLs. Pages that already have a current file are left alone. Options: --site={handle}, --limit={n}, and --queue to queue the warm instead of running it in the terminal. The command exits with an error when any page failed. Utilities → Parallelogram Cache queues the same warm, with progress in Craft's queue.

A page is warmed for the scheme and host in its URL: a purged page for the one it was cached under, and a provider's URL as the provider lists it. Behind Cloudflare that's https, matching the cache path visitors get through X-Forwarded-Proto. A URL that isn't absolute http or https can't be warmed and is reported. On the command line, where there's no request, the plugin sets @web from the warmBaseUrl setting (by default DEFAULT_SITE_URL) when nothing else has, so sites whose base URL is @web need no extra config.

Renders use the command-line PHP that runs the queue. When the queue runs inside the web server (Craft's automatic queue runner, under PHP-FPM), they fall back to php on the PATH; set PHP binary if that's the wrong one. A page that takes longer than Render timeout is stopped and reported. Failures are logged as warnings and don't stop the rest.

Per-visitor content

A cached page is the same for everyone, so anything that differs per visitor (a form's CSRF token, an enquiry count, a cart summary) is left as a placeholder and filled in after the page loads, from /p-cache/dynamic. That endpoint is never cached by the plugin, browsers or proxies.

Forms

Turn on Craft's asyncCsrfInputs in config/general.php. Every csrfInput(), including those Freeform and Formie write, then renders an empty <craft-csrf-input> that's filled with the visitor's own token once the page loads:

'asyncCsrfInputs' => true,

The plugin adds its filling script to every site page it renders, so those elements are also filled when a form arrives later, such as on a page a router swaps in, which Craft's own script (run once, on load) misses.

Or use pCache.csrfInput() instead of csrfInput() in a site's own forms:

<form method="post">
    {{ pCache.csrfInput() }}
    {{ actionInput('contact-form/send') }}
    ...
</form>

It writes the CSRF field with an empty value, filled with the visitor's own token once the page loads.

Without either, Craft's csrfInput() would bake one visitor's token into the cached page, and forms would then fail for everyone else. So a page isn't cached, and a warning names its URL, when it holds a real token (a form field named after csrfTokenName with a value, or a csrf-token meta tag with content) or its response says Cache-Control: no-store, no-cache or private (as Craft sends when it writes a token without asyncCsrfInputs).

A <meta name="csrf-token" content="" data-dynamic-fill="csrf" data-dynamic-fill-endpoint="/p-cache/dynamic"> tag is filled the same way, for scripts that read the token from there.

Fragments

Modules and plugins register named fragments:

use parallelogram\cache\dynamic\Fragment;
use parallelogram\cache\events\RegisterFragmentsEvent;
use parallelogram\cache\Plugin;
use yii\base\Event;

Event::on(Plugin::class, Plugin::EVENT_REGISTER_FRAGMENTS, static function (RegisterFragmentsEvent $event): void {
    // A plain value, shown as text: the number of items on the visitor's enquiry list.
    $event->fragments['enquiryCount'] = Fragment::value(
        static fn(): int => count(EnquiryList::forCurrentVisitor()->items),
    );

    // HTML from a site template, rendered for the visitor.
    $event->fragments['enquirySummary'] = Fragment::template('_partials/enquiry-summary');

    // HTML from a callable.
    $event->fragments['greeting'] = Fragment::html(
        static fn(): string => Craft::$app->getUser()->getIdentity() ? '<a href="/account">Your account</a>' : '',
    );
});

Names start with a letter, then letters, digits, _ or -, up to 64 characters; csrf is reserved. Templates place them with a fallback that shows until the fragment arrives, and stays if it can't:

<a href="/enquiry">Enquiry ({{ pCache.fragment('enquiryCount', '0') }})</a>
{{ pCache.fragment('enquirySummary', '', 'div') }}

fragment(name, fallback = '', tag = 'span') writes a <span> or <div>. A fragment that throws or returns the wrong kind of thing is left out of the response and logged, and the others still arrive.

The filling script

The plugin adds the script before </body> of every site page Craft renders while the plugin is enabled, so cached copies carry it. It fills the placeholders and <craft-csrf-input> elements with one request, and keeps watching the page so ones added later are filled with another. For a page whose HTML doesn't come through Craft's response, add it yourself (it runs once however often it's included):

{{ pCache.dynamicScript() }}
{# or, with a Content Security Policy: #}
{{ pCache.dynamicScript(nonce) }}

When the page has placeholders it makes one request to the endpoint, fills them, sets each one's data-dynamic-fill-status to filled or error, and dispatches p-cache:dynamic on document with the response as detail, or p-cache:dynamic-error with { error } if the request failed. A page cached with a nonce keeps that nonce, so a policy that changes it per request won't allow the script on cached pages; use a hash or 'self' with an external copy instead.

The endpoint

GET {site base URL}/p-cache/dynamic?fragments=a,b&csrf=1

  • fragments: names, comma-separated (or fragments[]=a&fragments[]=b). Unknown and badly formed names are ignored, duplicates are dropped, and at most 20 are answered.
  • csrf=1: also return the visitor's CSRF token. Leave it out on pages without forms; asking for a token sets Craft's CSRF cookie.

Response (application/json, Cache-Control: no-store, X-Robots-Tag: noindex):

{
    "fragments": {
        "enquiryCount": { "value": 3 },
        "enquirySummary": { "html": "<ul>…</ul>" }
    },
    "csrf": { "name": "CRAFT_CSRF_TOKEN", "value": "…" }
}

csrf is only present when asked for, and is null when CSRF protection is off. Each fragment is { "html": string } (set as the placeholder's HTML) or { "value": string|number|boolean|null } (set as its text; null empties it).

Contract for a ParallelogramJS component

A future ParallelogramJS DynamicFill component should match the fallback script, so templates don't change when a site switches. Following ParallelogramJS's component contracts:

Name DynamicFill
Kind enhancement
Selector data-dynamic-fill
Module components/DynamicFill

Attributes, all on the placeholder element:

Attribute Type Description
data-dynamic-fill string, required The fragment's name, or csrf for a CSRF field (<input>) or meta tag (<meta>).
data-dynamic-fill-endpoint string The endpoint's path for the page's site, written by the plugin. Defaults to /p-cache/dynamic.
data-dynamic-fill-status enum, read-only pending (as written), loading, then filled or error.

Behaviour:

  1. Collect every pending [data-dynamic-fill] element and <craft-csrf-input> on the page (including ones added later, as ParallelogramJS mounts them) and make one request per page and endpoint: fragments with the unique non-csrf names joined by commas, plus csrf=1 if any element is csrf. Send credentials: 'same-origin' and Accept: application/json.
  2. For csrf elements: set an <input>'s value, or a <meta>'s content, to csrf.value; replace a <craft-csrf-input> with a hidden input named csrf.name. Mark error when csrf is null or missing.
  3. For fragments: set innerHTML from html, or textContent from value (null empties it). Mark error when the name is missing from the response.
  4. On a failed request, mark every element error and keep its fallback.
  5. Do nothing when nothing is pending, and don't run alongside the plugin's script (it sets window.pCacheDynamic; the component should set the same flag).

Events, dispatched with ParallelogramJS's _dispatch on each element (channel: 'both'):

Event Detail When
dynamic-fill:filled { name: string } The element was filled.
dynamic-fill:error { name: string; error: unknown } The element couldn't be filled.

and once per page on document, as the fallback script does: p-cache:dynamic with the whole response as detail, or p-cache:dynamic-error with { error }.

Cloudflare edge caching

Off by default. When it's on, Cloudflare can keep cached pages at the edge, and every purge reaches the edge too.

Headers. A page that's cached (just stored, or sent from its file by PHP) gets:

Cache-Control: public, max-age=0, s-maxage=300
Cache-Tag: pc-all,pc-site-1,pc-3f2a9c0d1e8b7a64,…

Browsers never keep it (max-age=0), so a purge reaches every visitor on their next request; Cloudflare may keep it for s-maxage seconds (edgeMaxAge). Every other HTML response, including every page for a visitor with the bypass cookie, gets Cache-Control: private, no-store. Responses that aren't HTML, such as images, keep their own headers.

Tags. Each page carries {prefix}-all, {prefix}-site-{id}, and one tag per tag it used while rendering: {prefix}- and the first 16 hex characters of the tag's SHA-1. Craft's tags contain backslashes and can be long, while Cloudflare wants short printable ASCII without spaces and limits the Cache-Tag header to 16 KB (purge by tags). Tags that don't fit are left off; the page's URL is purged as well, so it can't go stale. Cloudflare strips Cache-Tag before responses reach visitors. Give each install that shares a zone (staging and production, say) its own edgeTagPrefix.

nginx. nginx can't read a page's tags, so with edge caching on, p-cache/nginx prints an include that sends every request to PHP, which answers cached pages from their files with their headers. Edge misses are rare (once per page, per Cloudflare location, per s-maxage), so this costs little. Regenerate the include whenever edge caching is turned on or off. The edge include also raises nginx's FastCGI buffers (fastcgi_buffer_size 32k; fastcgi_buffers 16 16k;): a page's Cache-Tag can reach Cloudflare's 16 KB limit, and nginx answers 502 when PHP's headers don't fit its default 4 or 8 KB buffer. Remove any fastcgi_buffer_size or fastcgi_buffers of your own from the same block, since nginx refuses a directive set twice.

Purges. After pages are purged from the cache folder, their edge tags and URLs wait in a table, and one delayed job (5 seconds) sends them to Cloudflare's purge API, 100 at a time. A save never waits on Cloudflare, and a burst of saves goes in as few requests as possible. A purge of everything becomes the {prefix}-all tag alone. A request that's rate limited or fails on Cloudflare's side is tried again up to three times, waiting as Retry-After asks; a job that still fails is retried by the queue, up to five attempts, and what wasn't purged stays waiting. p-cache/deploy purges {prefix}-all too. Until a failed purge goes through, Cloudflare serves the old page for at most edgeMaxAge seconds.

Purging by tag, hostname and prefix is available on every Cloudflare plan, with up to 100 items a request. The Free plan allows 5 such requests a minute (a burst of 25); Pro, 5 a second; Business, 10 a second. Purging by URL takes up to 100 URLs a request on all plans but Enterprise (purge cache limits).

Setting it up.

  1. Create an API token with the zone's Cache Purge and Zone Read permissions.
  2. Put it and the zone ID in .env, e.g. CLOUDFLARE_API_TOKEN and CLOUDFLARE_ZONE_ID, and set the settings to $CLOUDFLARE_API_TOKEN and $CLOUDFLARE_ZONE_ID. Keep the token itself out of project config.
  3. In Cloudflare, add a Cache Rule for the site's HTML with Eligible for cache, respecting origin Cache-Control (Cloudflare doesn't cache HTML by default).
  4. Turn on Cloudflare edge caching, then regenerate and reload the nginx include.
  5. Check Utilities → Cache diagnostics: the Cloudflare check confirms the token can read the zone.

Turning it off

Turning Cache pages off in the settings deletes every cached page. Disabling or uninstalling the plugin does the same. Pages already at Cloudflare's edge aren't purged then; they expire within edgeMaxAge seconds. When Blitz is installed alongside it for a comparison, turn Blitz's caching off and remove its nginx rules first.

Settings

All settings deploy with project config, or can be set in config/p-cache.php:

Setting Default Meaning
enabled true Store and serve pages. Turning it off deletes the cache.
cacheFolder cache/p-cache Inside the web root.
includedUris [['siteUid' => '', 'pattern' => '*']] Blitz-style patterns, explained below.
excludedUris [] Never cached, even when included.
queryParams [] Cached as their own variants. The pageTrigger parameter is added when Craft pages by query string.
ignoredParams ['utm_*', 'gclid', 'fbclid'] Still get the page's own file.
maxAge 7 Days before the sweep deletes a page.
stampVariable VERSION The environment variable holding the build stamp.
bypassCookie p-cache-bypass Name of the logged-in cookie.
refreshPurged true Warm purged pages again after a change.
refreshDelay 10 Seconds to wait after a purge before warming.
warmBatchSize 25 Pages each warming job renders.
warmTimeout 60 Seconds a page may take to render while warming.
warmBaseUrl '' The URL used for @web on the command line (warming, sweeping, queue runners), where there's no request to read it from. Takes $ENV_VAR. Empty uses DEFAULT_SITE_URL, or the primary site's base URL when that's absolute. A web request's own @web is never changed.
phpBinary '' The PHP command-line binary for warming renders. Empty uses the running one, or php on the PATH under PHP-FPM.
edgeCaching false Let Cloudflare keep cached pages at the edge, purged by tag.
cloudflareZoneId '' The zone ID, or $CLOUDFLARE_ZONE_ID.
cloudflareApiToken '' $CLOUDFLARE_API_TOKEN: a token with Cache Purge and Zone Read.
edgeMaxAge 300 Seconds Cloudflare may keep a page (s-maxage).
edgeTagPrefix pc Starts every edge tag; lowercase letters and digits, up to 16.

URI patterns work as in Blitz, so they import unchanged:

  • A pattern is a regular expression without delimiters, matched anywhere in the URI.
  • The URI has no leading slash, and is empty for the home page.
  • * on its own matches everything.
  • A row with an empty site UID applies to every site.

Development

composer install
composer check

The Craft integration suite runs from the sandbox project, under the pca_ table prefix in craft_images_test:

cd ../parallelogram-craft-sandbox
bash ../parallelogram-craft-cache/test/Craft/install-test-db.sh
vendor/bin/phpunit -c ../parallelogram-craft-cache/phpunit.craft.xml