Dev.to WebDev 🛠 Dev 👁 0 📖 23 min read

Audit Caching and Compression Headers Across Your Sitemap with Python: Cache-Control, gzip, Vary, ETags, 304s, Versioned Assets

Speed tools usually test one page at a time, and the page you test is usually the homepage. Caching and compression problems hide elsewhere: a blog that runs on an older install and sends uncompressed HTML, a booking wid

Speed tools usually test one page at a time, and the page you test is usually the homepage. Caching and compression problems hide elsewhere: a blog that runs on an older install and sends uncompressed HTML, a booking widget script with no cache headers at all, a stylesheet with a version hash in its name that the server still expires after ten minutes, or a JavaScript file with no version in its name that the server tells browsers to keep for a year. If you look after sites for clients (a small agency with a handful of local business sites, say), you want one run per site that checks every page and every file those pages load.

This post builds that check in Python with only the standard library (urllib, gzip, html.parser, xml.etree, csv, concurrent.futures). You give it a sitemap. It fetches every page, collects the stylesheets, scripts, images and icons each page loads, fetches those once each, and flags:

  • HTML, CSS, JavaScript and SVG sent without compression
  • compressed responses without Vary: Accept-Encoding
  • JPEGs, PNGs, WebP and fonts gzipped again even though they are already compressed
  • pages with no Cache-Control, and HTML pages cached for days
  • pages with no ETag or Last-Modified, and servers that ignore conditional requests (200 instead of 304)
  • static files with no cache policy (or only an Expires date)
  • files with a version hash in the name but a short cache lifetime
  • files without a version in the name but a year-long or immutable cache lifetime
  • pages that fall into different caching groups (often a sign of a second app or theme)

It writes a CSV with one row per issue and prints a summary. Every output below comes from a real run against a small fictional test site on localhost, which you can rebuild from the code in this post.

Sources opened on 25 Nov 2026: MDN's reference pages for Cache-Control, Content-Encoding, Vary, ETag and Expires, MDN's HTTP caching guide, RFC 9111 (HTTP Caching) and Chrome's Lighthouse page Serve static assets with an efficient cache policy. The test site ("Brightwater Plumbing & Heating") is fictional and runs on localhost. Appie free-tool descriptions are as of 25 Nov 2026, checked on the tool's page that day.

Disclosure: Appie.run publishes this article. One free tool mentioned near the end is ours. The script does not depend on it.

What this is (and is not)

It is a header audit: what the server says about compression and caching for each page and file. It is not a full performance test. It does not measure load times, Core Web Vitals or image dimensions, and it does not look at CDN edge settings you cannot see in response headers. It only requests gzip, because Python's standard library cannot decode Brotli; a server that offers Brotli to browsers almost always offers gzip too, so a page that comes back uncompressed here is worth a look.

What the references say

Always send Cache-Control. MDN's caching guide explains that without Cache-Control, browsers fall back to "heuristic caching" based on Last-Modified, and says "basically all responses should explicitly specify a Cache-Control header." The script flags pages and files without it.

Expires is the older way. MDN's Expires page notes that "If there is a Cache-Control header with the max-age or s-maxage directive in the response, the Expires header is ignored." A file with only an Expires date in the past is effectively not cached, so the script treats Expires-only files as having no real cache policy and shows the date in the report.

HTML and static files want different rules. MDN's Cache-Control page describes the "cache busting" pattern: put a version or hash in the file name or query string, give those files a long max-age and immutable, and serve the HTML with no-cache so browsers check for a new version each time. Lighthouse makes the same point: "cache immutable static assets for a long time, such as a year or longer," and warns that long lifetimes on files without a hash mean "your users won't see updates to static files." That gives two opposite mistakes, and the script flags both: a versioned file with a short lifetime, and an unversioned file with a long one.

Validators make revalidation cheap. With an ETag or Last-Modified, a browser can ask "has this changed?" and get a small 304 Not Modified instead of the full page. The script sends If-None-Match (or If-Modified-Since) back and flags servers that answer 200 anyway.

Compress text, not images. MDN's Content-Encoding page says servers "should compress data as much as possible," and also that "Compressing already compressed media types, such as .zip or .jpeg, is usually not appropriate because it can increase the file size."

Vary goes with compression. MDN's Vary page says the header "ensures that responses are separately cached based on the headers listed in the Vary field." When a server compresses depending on Accept-Encoding, it should say so with Vary: Accept-Encoding, so a shared cache does not hand a gzipped copy to a client that did not ask for one.

How the audit works

  1. Read the sitemap (following a sitemap index if there is one).
  2. Fetch each page with Accept-Encoding: gzip and look at Content-Encoding, Vary, Cache-Control, ETag and Last-Modified.
  3. If the page has a validator, send a conditional request and expect a 304.
  4. Decompress the HTML and collect same-origin stylesheets, scripts, images, icons and preloads.
  5. Fetch each file once and check compression and cache policy, using the file name to decide whether it is versioned.
  6. Write a CSV (with the pages each file is used on), print counts, and group pages by their caching and compression headers.

Small bodies (under 1,400 bytes, roughly one network packet) are not flagged for missing compression.

The script

Save as cache_audit.py:

#!/usr/bin/env python3
"""Audit caching and compression headers for every page in a sitemap and the assets those pages load.

Standard library only. Usage:
    python3 cache_audit.py https://example.com/sitemap.xml --csv cache_report.csv
"""
import argparse, csv, gzip, re, sys, urllib.error, urllib.request, zlib
import xml.etree.ElementTree as ET
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor
from html.parser import HTMLParser
from urllib.parse import urljoin, urlsplit

UA = "cache-compression-audit/1.0 (+https://dev.to/appierun_66)"
NS = "{http://www.sitemaps.org/schemas/sitemap/0.9}"
DAY, MONTH, YEAR = 86400, 30 * 86400, 365 * 86400
MIN_COMPRESS = 1400  # bytes; smaller bodies fit in about one packet, so compression matters little
TEXT_TYPES = ("text/", "application/javascript", "application/json", "application/xml",
              "image/svg+xml", "application/manifest+json")
PRECOMPRESSED = ("image/jpeg", "image/png", "image/webp", "image/avif", "image/gif",
                 "font/woff2", "font/woff", "video/", "audio/", "application/zip", "application/pdf")
# A hash or version in the file name or query string, e.g. site.3f9a1c7e.css or app.js?v=12
FINGERPRINT = re.compile(r"[.\-_][0-9a-f]{6,}[.\-_]|[?&](v|ver|version|hash|h)=", re.I)
SEVERITY_ORDER = {"high": 0, "medium": 1, "low": 2, "info": 3}


def fetch(url, extra=None, timeout=15):
    """GET with Accept-Encoding: gzip. Returns (status, headers dict lower-cased, raw body bytes)."""
    hdrs = {"User-Agent": UA, "Accept-Encoding": "gzip"}
    hdrs.update(extra or {})
    req = urllib.request.Request(url, headers=hdrs)
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return r.status, {k.lower(): v for k, v in r.headers.items()}, r.read()
    except urllib.error.HTTPError as e:
        return e.code, {k.lower(): v for k, v in (e.headers or {}).items()}, b""
    except Exception as e:
        return None, {"x-audit-error": str(e)[:120]}, b""


def decode(headers, body):
    enc = headers.get("content-encoding", "").lower()
    if enc == "gzip":
        return gzip.decompress(body)
    if enc == "deflate":
        return zlib.decompress(body)
    return body


def sitemap_urls(url, seen=None):
    seen = seen or set()
    if url in seen:
        return []
    seen.add(url)
    status, headers, body = fetch(url)
    root = ET.fromstring(decode(headers, body))
    if root.tag == NS + "sitemapindex":
        out = []
        for loc in root.iter(NS + "loc"):
            out += sitemap_urls(loc.text.strip(), seen)
        return out
    return [loc.text.strip() for loc in root.iter(NS + "loc")]


class AssetParser(HTMLParser):
    """Collect stylesheets, scripts, images and icons a page loads."""
    def __init__(self):
        super().__init__()
        self.assets = []
    def handle_starttag(self, tag, attrs):
        a = dict(attrs)
        if tag == "script" and a.get("src"):
            self.assets.append(a["src"])
        elif tag == "img" and a.get("src"):
            self.assets.append(a["src"])
        elif tag == "link" and a.get("href"):
            rel = (a.get("rel") or "").lower()
            if any(x in rel for x in ("stylesheet", "icon", "preload", "modulepreload")):
                self.assets.append(a["href"])


def cache_control(headers):
    out = {}
    for part in headers.get("cache-control", "").split(","):
        part = part.strip().lower()
        if part:
            k, _, v = part.partition("=")
            out[k.strip()] = v.strip().strip('"')
    return out


def max_age(cc):
    try:
        return int(cc.get("max-age", ""))
    except ValueError:
        return None


def media_type(headers):
    return headers.get("content-type", "").split(";")[0].strip().lower()


def compression_issues(url, kind, headers, body):
    out = []
    mtype = media_type(headers)
    enc = headers.get("content-encoding", "").lower()
    vary = headers.get("vary", "").lower()
    if not enc and mtype.startswith(TEXT_TYPES) and len(body) >= MIN_COMPRESS:
        sev = "medium"
        out.append((url, kind, sev, f"{kind}_not_compressed",
                    f"{mtype}, {len(body):,} bytes sent without Content-Encoding"))
    if enc and mtype.startswith(PRECOMPRESSED):
        out.append((url, kind, "low", "precompressed_type_gzipped",
                    f"{mtype} sent with Content-Encoding: {enc}; it is already compressed"))
    if enc and "accept-encoding" not in vary and "*" not in vary:
        out.append((url, kind, "low", "vary_missing",
                    f"Content-Encoding: {enc} but Vary is '{headers.get('vary', '')}'"))
    return out


def check_page(url):
    status, headers, raw = fetch(url)
    issues = []
    if status != 200:
        return url, status, headers, [], [(url, "page", "info", "not_200", f"status {status}")]
    body = decode(headers, raw)
    cc = cache_control(headers)
    issues += compression_issues(url, "page", headers, raw)
    if "cache-control" not in headers:
        note = "Expires only" if "expires" in headers else "browsers fall back to heuristic caching"
        issues.append((url, "page", "low", "cache_control_missing", note))
    if "no-store" in cc:
        issues.append((url, "page", "info", "page_no_store",
                       "no-store: fine for account or checkout pages, worth a check on public pages"))
    ma = max_age(cc)
    if ma is not None and ma > DAY and "no-cache" not in cc:
        issues.append((url, "page", "medium", "page_long_max_age",
                       f"HTML cached for {ma // DAY} days; edits may not reach repeat visitors"))
    issues += validator_issues(url, "page", headers)
    assets = []
    if "html" in media_type(headers):
        p = AssetParser()
        p.feed(body.decode("utf-8", "replace"))
        assets = [urljoin(url, a) for a in p.assets]
    return url, status, headers, assets, issues


def validator_issues(url, kind, headers):
    etag, lastmod = headers.get("etag"), headers.get("last-modified")
    if not etag and not lastmod:
        return [(url, kind, "low", "no_validator", "no ETag or Last-Modified, so no cheap 304 revalidation")]
    cond = {"If-None-Match": etag} if etag else {"If-Modified-Since": lastmod}
    status, _, _ = fetch(url, cond)
    if status == 200:
        used = "If-None-Match" if etag else "If-Modified-Since"
        return [(url, kind, "low", "conditional_ignored", f"{used} sent, got 200 instead of 304")]
    return []


def check_asset(url):
    status, headers, raw = fetch(url)
    if status != 200:
        return url, headers, [(url, "asset", "info", "not_200", f"status {status}")]
    issues = compression_issues(url, "asset", headers, raw)
    cc = cache_control(headers)
    ma = max_age(cc)
    fingerprinted = bool(FINGERPRINT.search(urlsplit(url).path + "?" + urlsplit(url).query))
    if "cache-control" not in headers:
        note = f"Expires: {headers['expires']}" if "expires" in headers else "no Cache-Control or Expires"
        issues.append((url, "asset", "medium", "asset_no_cache_policy", note))
    elif "no-store" in cc:
        issues.append((url, "asset", "medium", "asset_no_store", "no-store on a static file"))
    elif fingerprinted and (ma or 0) < MONTH:
        issues.append((url, "asset", "medium", "fingerprinted_short_cache",
                       f"versioned file name but max-age={ma}; it can be cached for a year"))
    elif not fingerprinted and ("immutable" in cc or (ma or 0) >= MONTH):
        issues.append((url, "asset", "medium", "unversioned_long_cache",
                       f"'{headers['cache-control']}' on a file name without a version; "
                       "visitors may keep the old file after you change it"))
    return url, headers, issues


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("sitemap")
    ap.add_argument("--csv", default="cache_report.csv")
    ap.add_argument("--workers", type=int, default=4)
    ap.add_argument("--third-party", action="store_true", help="also check assets on other hosts")
    args = ap.parse_args()

    urls = sitemap_urls(args.sitemap)
    host = urlsplit(args.sitemap).netloc
    with ThreadPoolExecutor(args.workers) as ex:
        pages = list(ex.map(check_page, urls))

    issues, asset_pages = [], defaultdict(set)
    for url, status, headers, assets, page_issues in pages:
        issues += page_issues
        for a in assets:
            if args.third_party or urlsplit(a).netloc == host:
                asset_pages[a].add(urlsplit(url).path or "/")
    with ThreadPoolExecutor(args.workers) as ex:
        asset_results = list(ex.map(check_asset, sorted(asset_pages)))
    for url, headers, asset_issues in asset_results:
        issues += asset_issues

    issues.sort(key=lambda i: (SEVERITY_ORDER[i[2]], i[3], i[0]))
    with open(args.csv, "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["url", "kind", "severity", "issue", "detail", "used_on_pages"])
        for u, kind, sev, code, detail in issues:
            used = " ".join(sorted(asset_pages.get(u, []))) if kind == "asset" else ""
            w.writerow([u, kind, sev, code, detail, used])

    flagged_pages = {i[0] for i in issues if i[1] == "page"}
    flagged_assets = {i[0] for i in issues if i[1] == "asset"}
    print(f"Checked {len(urls)} pages and {len(asset_pages)} assets from {args.sitemap}")
    print(f"{len(flagged_pages)} of {len(urls)} pages and {len(flagged_assets)} of {len(asset_pages)} assets "
          f"have at least one issue\n")
    counts = Counter((i[2], i[3]) for i in issues)
    for (sev, code), n in sorted(counts.items(), key=lambda x: (SEVERITY_ORDER[x[0][0]], -x[1], x[0][1])):
        print(f"  {sev:<6} {code:<28} {n}")

    groups = defaultdict(list)
    for url, status, headers, assets, _ in pages:
        if status == 200:
            key = (headers.get("cache-control", "(none)"), headers.get("content-encoding", "(none)"))
            groups[key].append(urlsplit(url).path or "/")
    if len(groups) > 1:
        print("\nPages grouped by Cache-Control / Content-Encoding (different groups often mean a second app):")
        for (cc, enc), paths in sorted(groups.items(), key=lambda g: -len(g[1])):
            shown = ", ".join(paths[:4]) + (" ..." if len(paths) > 4 else "")
            print(f"  {cc} / {enc}: {len(paths)} page(s): {shown}")
    print(f"\nDetails: {args.csv}")


if __name__ == "__main__":
    sys.exit(main())

A few choices worth knowing:

  • "Versioned" is a guess from the URL. The regex looks for a hex hash of 6+ characters between dots, dashes or underscores (site.3f9a1c7e.css, application-5aac8c55.js) or a v=, ver=, version=, hash= or h= query parameter. If your build uses another pattern, change FINGERPRINT.
  • Thresholds. A versioned file under 30 days is flagged; an unversioned file at 30 days or more (or immutable) is flagged; HTML over one day without no-cache is flagged. Lighthouse suggests a year for versioned files; 30 days is a lower bar for "clearly too short."
  • Same-origin files only by default. Third-party scripts (analytics, chat widgets, maps) are outside your control. Add --third-party to include them.
  • no-store on a page is info, not an error. It is right for account, checkout and some booking pages. On a public service page it means every visit downloads everything again.

The test site

The fixture is a fictional plumbing company with eight pages and six files. Most pages come from a theme that gets the basics right. The blog runs on an older setup. A few files were configured by hand at different times.

build_fixture.py writes the pages, assets and sitemap:

"""Build the fictional "Brightwater Plumbing & Heating" test site in ./site (served on localhost:8494)."""
import os

BASE = "http://localhost:8494"
os.makedirs("site/assets", exist_ok=True)
os.makedirs("site/blog-assets", exist_ok=True)

FILLER = ("Brightwater is a fictional plumbing and heating company used to test this script. "
          "We fix boilers, clear drains and service radiators for homes across a made-up town. ") * 12

def page(title, body, blog=False):
    css = "/blog-assets/blog.css" if blog else "/assets/site.3f9a1c7e.css"
    js = "" if blog else '<script src="/assets/app.js" defer></script>'
    widget = '<script src="/assets/booking-widget.js" defer></script>' if title == "Contact" else ""
    return f"""<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>{title} | Brightwater Plumbing & Heating</title>
<link rel="stylesheet" href="{css}"><link rel="icon" href="/assets/logo.svg">{js}{widget}</head>
<body><header><img src="/assets/logo.svg" alt="Brightwater"></header>
<main><h1>{title}</h1><img src="/assets/hero.jpg" alt="Van outside a house"><p>{body}</p><p>{FILLER}</p></main>
<footer><p>Brightwater Plumbing & Heating (fictional test site)</p></footer></body></html>
"""

PAGES = {
    "index.html": page("Brightwater Plumbing & Heating", "Boilers, drains and radiators."),
    "services.html": page("Services", "Everything we do."),
    "services__boiler-repair.html": page("Boiler repair", "Same-week boiler repairs."),
    "services__drain-cleaning.html": page("Drain cleaning", "Blocked sinks, showers and outside drains."),
    "about.html": page("About", "A small team of engineers."),
    "contact.html": page("Contact", "Book a visit with the form below."),
    "blog.html": page("Blog", "Tips for keeping your heating running.", blog=True),
    "blog__winter-pipe-checklist.html": page("Winter pipe checklist", "Lag outside pipes before the first frost.", blog=True),
}
for name, html in PAGES.items():
    open(os.path.join("site", name), "w").write(html)

rule = "body{font-family:system-ui,sans-serif;margin:0;color:#1d2a33}.btn{padding:.6rem 1rem;border-radius:6px}\n"
open("site/assets/site.3f9a1c7e.css", "w").write(rule * 60)
open("site/blog-assets/blog.css", "w").write(rule.replace("system-ui", "Georgia") * 50)
open("site/assets/app.js", "w").write("document.querySelectorAll('.btn').forEach(function(b){b.addEventListener('click',function(){b.blur();});});\n" * 40)
open("site/assets/booking-widget.js", "w").write("window.bookingWidget={open:function(){console.log('open booking form');}};\n" * 40)
open("site/assets/logo.svg", "w").write('<svg xmlns="http://www.w3.org/2000/svg" width="120" height="40">'
    + "".join(f'<rect x="{i}" y="0" width="1" height="40" fill="#0b6e99"/>' for i in range(60)) + "</svg>")
# A small binary "photo": random bytes stand in for an already-compressed JPEG.
open("site/assets/hero.jpg", "wb").write(b"\xff\xd8\xff\xe0" + os.urandom(24000) + b"\xff\xd9")

urls = ["/", "/services", "/services/boiler-repair", "/services/drain-cleaning", "/about", "/contact",
        "/blog", "/blog/winter-pipe-checklist"]
open("site/sitemap.xml", "w").write('<?xml version="1.0" encoding="UTF-8"?>\n'
    '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
    + "".join(f"  <url><loc>{BASE}{u}</loc></url>\n" for u in urls) + "</urlset>\n")
print("built", len(PAGES), "pages")

serve_fixture.py serves it on localhost:8494 and applies caching and compression rules per path from a JSON file, so the same site can run "before" and "after":

"""Serve ./site on localhost:8494. Caching and compression behaviour per path comes from the
JSON rules file given as the first argument (first matching rule wins)."""
import email.utils, gzip, hashlib, http.server, json, mimetypes, os, sys

RULES = json.load(open(sys.argv[1] if len(sys.argv) > 1 else "rules-before.json"))
mimetypes.add_type("image/svg+xml", ".svg")

def rule_for(path):
    for r in RULES:
        if path == r["match"] or (r["match"].endswith("*") and path.startswith(r["match"][:-1])):
            return r
    return {}

def file_for(path):
    if path == "/":
        return "site/index.html"
    if os.path.splitext(path)[1]:
        return "site" + path
    return "site/" + path.strip("/").replace("/", "__") + ".html"

class Handler(http.server.BaseHTTPRequestHandler):
    server_version, sys_version = "fixture", ""
    def log_message(self, *a):
        pass
    def do_GET(self):
        path = self.path.split("?")[0].split("#")[0]
        path = path.rstrip("/") or "/"
        fn = file_for(path)
        if not os.path.isfile(fn):
            self.send_response(404); self.send_header("Content-Length", "0"); self.end_headers(); return
        body = open(fn, "rb").read()
        r = rule_for(path)
        ctype = mimetypes.guess_type(fn)[0] or "application/octet-stream"
        if ctype.startswith("text/") or ctype.endswith(("xml", "javascript")):
            ctype += "; charset=utf-8"
        etag = '"%s"' % hashlib.sha1(body).hexdigest()[:16]
        lastmod = email.utils.formatdate(os.path.getmtime(fn), usegmt=True)
        if r.get("honor_conditional"):
            if r.get("etag") and self.headers.get("If-None-Match") == etag or \
               r.get("last_modified") and self.headers.get("If-Modified-Since") == lastmod:
                self.send_response(304)
                if r.get("etag"): self.send_header("ETag", etag)
                for k, v in r.get("headers", {}).items(): self.send_header(k, v)
                self.end_headers(); return
        if r.get("gzip") and "gzip" in self.headers.get("Accept-Encoding", ""):
            body = gzip.compress(body)
            self.send_response(200); self.send_header("Content-Encoding", "gzip")
        else:
            self.send_response(200)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(body)))
        if r.get("etag"): self.send_header("ETag", etag)
        if r.get("last_modified"): self.send_header("Last-Modified", lastmod)
        for k, v in r.get("headers", {}).items(): self.send_header(k, v)
        self.end_headers()
        self.wfile.write(body)

http.server.ThreadingHTTPServer(("127.0.0.1", 8494), Handler).serve_forever()

The "before" rules (rules-before.json). The blog sends no cache headers, ignores conditional requests and skips compression. The services pages compress but forget Vary. The About page is cached for a week. The contact page uses no-store. The versioned stylesheet expires after 10 minutes, the unversioned app.js is marked immutable for a year, the booking widget and blog stylesheet have no real cache policy, the SVG logo is not compressed and the JPEG is gzipped:

[
 {
  "match": "/sitemap.xml",
  "gzip": true,
  "etag": true,
  "honor_conditional": true,
  "headers": {
   "Cache-Control": "no-cache",
   "Vary": "Accept-Encoding"
  }
 },
 {
  "match": "/contact",
  "gzip": true,
  "etag": true,
  "honor_conditional": true,
  "headers": {
   "Cache-Control": "no-store",
   "Vary": "Accept-Encoding"
  }
 },
 {
  "match": "/services*",
  "gzip": true,
  "etag": true,
  "honor_conditional": true,
  "headers": {
   "Cache-Control": "no-cache"
  }
 },
 {
  "match": "/blog-assets/*",
  "gzip": false,
  "last_modified": true,
  "headers": {
   "Expires": "Thu, 01 Jan 2026 00:00:00 GMT",
   "Pragma": "no-cache"
  }
 },
 {
  "match": "/blog*",
  "gzip": false,
  "last_modified": true,
  "honor_conditional": false,
  "headers": {}
 },
 {
  "match": "/about",
  "gzip": true,
  "etag": true,
  "honor_conditional": true,
  "headers": {
   "Cache-Control": "public, max-age=604800",
   "Vary": "Accept-Encoding"
  }
 },
 {
  "match": "/assets/site.3f9a1c7e.css",
  "gzip": true,
  "etag": true,
  "honor_conditional": true,
  "headers": {
   "Cache-Control": "max-age=600",
   "Vary": "Accept-Encoding"
  }
 },
 {
  "match": "/assets/app.js",
  "gzip": true,
  "etag": true,
  "honor_conditional": true,
  "headers": {
   "Cache-Control": "public, max-age=31536000, immutable",
   "Vary": "Accept-Encoding"
  }
 },
 {
  "match": "/assets/booking-widget.js",
  "gzip": false,
  "headers": {}
 },
 {
  "match": "/assets/hero.jpg",
  "gzip": true,
  "etag": true,
  "honor_conditional": true,
  "headers": {
   "Vary": "Accept-Encoding"
  }
 },
 {
  "match": "/assets/logo.svg",
  "gzip": false,
  "etag": true,
  "honor_conditional": true,
  "headers": {
   "Cache-Control": "max-age=86400"
  }
 },
 {
  "match": "/*",
  "gzip": true,
  "etag": true,
  "honor_conditional": true,
  "headers": {
   "Cache-Control": "no-cache",
   "Vary": "Accept-Encoding"
  }
 }
]

And a small shell wrapper, serve_fixture.sh:

#!/bin/sh
# Usage: ./serve_fixture.sh [--fixed]   (HTTP on localhost:8494)
cd "$(dirname "$0")"
[ -d site ] || python3 build_fixture.py
if [ "$1" = "--fixed" ]; then exec python3 serve_fixture.py rules-after.json; else exec python3 serve_fixture.py rules-before.json; fi

Running it

./serve_fixture.sh &
python3 cache_audit.py http://localhost:8494/sitemap.xml --csv cache_report_before.csv

Output:

Checked 8 pages and 6 assets from http://localhost:8494/sitemap.xml
7 of 8 pages and 6 of 6 assets have at least one issue

  medium asset_no_cache_policy        3
  medium asset_not_compressed         3
  medium page_not_compressed          2
  medium fingerprinted_short_cache    1
  medium page_long_max_age            1
  medium unversioned_long_cache       1
  low    vary_missing                 3
  low    cache_control_missing        2
  low    conditional_ignored          2
  low    precompressed_type_gzipped   1
  info   page_no_store                1

Pages grouped by Cache-Control / Content-Encoding (different groups often mean a second app):
  no-cache / gzip: 4 page(s): /, /services, /services/boiler-repair, /services/drain-cleaning
  (none) / (none): 2 page(s): /blog, /blog/winter-pipe-checklist
  public, max-age=604800 / gzip: 1 page(s): /about
  no-store / gzip: 1 page(s): /contact

Details: cache_report_before.csv

The grouping block tells the story faster than the counts. Four pages share the theme's no-cache with gzip. The blog sends nothing at all, which points to a second app. The About and Contact pages each have their own setting, which usually means someone changed them by hand.

A few rows from cache_report_before.csv:

url,kind,severity,issue,detail,used_on_pages
http://localhost:8494/blog-assets/blog.css,asset,medium,asset_no_cache_policy,"Expires: Thu, 01 Jan 2026 00:00:00 GMT",/blog /blog/winter-pipe-checklist
http://localhost:8494/assets/site.3f9a1c7e.css,asset,medium,fingerprinted_short_cache,versioned file name but max-age=600; it can be cached for a year,/ /about /contact /services /services/boiler-repair /services/drain-cleaning
http://localhost:8494/assets/app.js,asset,medium,unversioned_long_cache,"'public, max-age=31536000, immutable' on a file name without a version; visitors may keep the old file after you change it",/ /about /contact /services /services/boiler-repair /services/drain-cleaning
http://localhost:8494/blog,page,low,conditional_ignored,"If-Modified-Since sent, got 200 instead of 304",
http://localhost:8494/assets/hero.jpg,asset,low,precompressed_type_gzipped,image/jpeg sent with Content-Encoding: gzip; it is already compressed,/ /about /blog /blog/winter-pipe-checklist /contact /services /services/boiler-repair /services/drain-cleaning
http://localhost:8494/services,page,low,vary_missing,Content-Encoding: gzip but Vary is '',

Two rows deserve a closer look:

  • blog.css with Expires: Thu, 01 Jan 2026. The date is in the past, so the file is stale the moment it arrives. This is common on old setups where someone once set a fixed date and forgot it.
  • app.js with immutable and no version in the name. This is the one that causes "I changed the site but the client still sees the old menu" calls. Browsers that cached it will keep the old file for up to a year unless the URL changes.

Fixing it and running again

The fixes, in rules-after.json:

  • versioned stylesheet: public, max-age=31536000, immutable
  • unversioned app.js and the booking widget: public, max-age=3600 (or rename them with a hash in your build and then cache for a year)
  • blog: compression on, ETag, Cache-Control: no-cache, conditional requests honored, blog stylesheet compressed with an hour of caching
  • services pages: Vary: Accept-Encoding
  • About page: no-cache like the rest of the HTML
  • contact page: no-cache (the form page holds no private data in this fixture; keep no-store where it does)
  • JPEG: no gzip, one day of caching; SVG logo: gzip with Vary
[
  {"match": "/sitemap.xml", "gzip": true, "etag": true, "honor_conditional": true,
   "headers": {"Cache-Control": "no-cache", "Vary": "Accept-Encoding"}},
  {"match": "/contact", "gzip": true, "etag": true, "honor_conditional": true,
   "headers": {"Cache-Control": "no-cache", "Vary": "Accept-Encoding"}},
  {"match": "/assets/site.3f9a1c7e.css", "gzip": true, "etag": true, "honor_conditional": true,
   "headers": {"Cache-Control": "public, max-age=31536000, immutable", "Vary": "Accept-Encoding"}},
  {"match": "/assets/app.js", "gzip": true, "etag": true, "honor_conditional": true,
   "headers": {"Cache-Control": "public, max-age=3600", "Vary": "Accept-Encoding"}},
  {"match": "/assets/booking-widget.js", "gzip": true, "etag": true, "honor_conditional": true,
   "headers": {"Cache-Control": "public, max-age=3600", "Vary": "Accept-Encoding"}},
  {"match": "/assets/hero.jpg", "gzip": false, "etag": true, "honor_conditional": true,
   "headers": {"Cache-Control": "public, max-age=86400"}},
  {"match": "/assets/logo.svg", "gzip": true, "etag": true, "honor_conditional": true,
   "headers": {"Cache-Control": "public, max-age=86400", "Vary": "Accept-Encoding"}},
  {"match": "/blog-assets/*", "gzip": true, "etag": true, "honor_conditional": true,
   "headers": {"Cache-Control": "public, max-age=3600", "Vary": "Accept-Encoding"}},
  {"match": "/*", "gzip": true, "etag": true, "honor_conditional": true,
   "headers": {"Cache-Control": "no-cache", "Vary": "Accept-Encoding"}}
]
./serve_fixture.sh --fixed &
python3 cache_audit.py http://localhost:8494/sitemap.xml --csv cache_report_after.csv
Checked 8 pages and 6 assets from http://localhost:8494/sitemap.xml
0 of 8 pages and 0 of 6 assets have at least one issue


Details: cache_report_after.csv

On a real server, these changes usually live in one or two places: the web server or CDN config for static files (by path or extension), and the CMS or app for HTML. On WordPress-style setups, a caching plugin and the host's settings may both add headers, so check the response after each change, not the settings screen.

Running it on a client site

  • Ask first. Run it only on sites you look after or have permission to test. It sends one or two requests per page and one per file, which is light, but it is still traffic.
  • Use the root sitemap. The script follows a sitemap index, so point it at the top-level file.
  • Read the grouping block first. If the blog, a booking plugin or a landing-page builder sits in its own group, fix it where those pages are served.
  • Check what the CDN changes. Some CDNs add or rewrite Cache-Control, Vary and compression at the edge. The script sees what a visitor sees, which is what matters, but the fix may be in the CDN dashboard rather than the server.
  • Do not cache logged-in pages publicly. If a page shows anything personal, keep private or no-store on it. The script only reads public pages from the sitemap.
  • Be polite. The default is 4 workers. Use --workers 2 on small shared hosting.

What to fix first

  1. page_not_compressed and asset_not_compressed. Usually one server setting, and it shrinks every text response.
  2. unversioned_long_cache. The one that makes updates invisible. Shorten the lifetime or add a hash to the file name.
  3. asset_no_cache_policy and fingerprinted_short_cache. Repeat visitors re-download files that never change.
  4. page_long_max_age. HTML cached for days hides edits; prefer no-cache plus an ETag.
  5. The low and info rows. Vary, validators, 304 support, gzipped JPEGs and no-store checks, best done in one pass.

Related free tool

Before you audit a client site you need its sitemap URL, and older sites sometimes keep it somewhere unusual. Our free Sitemap Finder and Checker takes a site URL, reads robots.txt and the usual sitemap paths (including the WordPress path), and reports which files load and how many URLs they list. It does not look at headers; that is what the script is for.

If you are working through a client site's response headers anyway, our earlier post on finding mixed content across your sitemap is a good companion, and the image weight audit covers the bytes this script does not.

FAQ

Should HTML pages have a long max-age?
Usually not. MDN's cache-busting example serves the HTML with no-cache so browsers revalidate it each time and pick up new versioned assets. With an ETag, that revalidation is a small 304 when nothing changed.

What does immutable do?
MDN describes it as telling a cache the response "will not be updated while it's fresh," which avoids revalidation on reload. Use it only on URLs that change whenever the content changes.

Why flag gzip on JPEG files?
MDN says compressing already compressed types such as .jpeg "is usually not appropriate because it can increase the file size." In the fixture, where random bytes stand in for a JPEG's already-compressed data, gzip made the file 28 bytes larger (24,006 to 24,034).

Is Expires still needed?
Not if you send Cache-Control with max-age; MDN notes Expires is then ignored. An Expires date in the past makes the response stale immediately.

Does a clean report mean the site is fast?
No. It means the pages and files in the sitemap are compressed and have sensible caching headers. Image sizes, server response time, third-party scripts and layout still need their own checks.

If you are onboarding a new client site, our free Sitemap Finder and Checker finds the sitemap in one step, so you can point this script at the right file.

RG, Founder, Appie.run

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.