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

Your sitemap lastmod Is Lying. Here's a 40-Line Fix That Made Mine Honest

If your site is built from templates, there is a good chance every page in your sitemap has the same lastmod date — the date of your last deploy. That is not a lie you tell on purpose. It falls out of the build: a foote

If your site is built from templates, there is a good chance every page in your sitemap has the same lastmod date — the date of your last deploy.

That is not a lie you tell on purpose. It falls out of the build: a footer change touches all 1,287 files, the generator stamps each one with now(), and the sitemap faithfully reports that the entire site changed at 14:32 on Tuesday.

To a crawler, that means: nothing here is more important than anything else. So it re-checks everything, in whatever order it feels like, and the pages you actually care about wait in the same queue as the ones nobody will ever link to.

I had exactly this. Search Console told me 51% of my crawl budget was going to Refresh and 49% to Discovery, with 299 pages sitting in Discovered - currently not indexed.

The fix is not a new build system. It is a content hash.

The idea

lastmod should answer one question: did the part of this page a visitor reads actually change?

Not "did the file change" — the file changes every time a template fragment moves. Not "did the build run" — the build runs constantly.

Just: did <main> change.

So: extract the meaningful body of each page, hash it, store the hash, and only bump lastmod when the hash differs.

The extractor

import hashlib
import re
from pathlib import Path

# Everything between <main> and </main>, minus blocks that are shared
# across the whole site and therefore change on every template edit.
STRIP_BLOCKS = [
    re.compile(r'<nav\b.*?</nav>', re.S | re.I),
    re.compile(r'<footer\b.*?</footer>', re.S | re.I),
    re.compile(r'<div class="cta-band".*?</div>\s*</div>', re.S | re.I),
    re.compile(r'<!--.*?-->', re.S),
]

WS = re.compile(r'\s+')


def body_fingerprint(path: Path) -> str:
    html = path.read_text(encoding='utf-8', errors='replace')

    m = re.search(r'<main\b[^>]*>(.*?)</main>', html, re.S | re.I)
    if not m:
        # Pages without <main> fall back to <body> minus the shared chrome.
        m = re.search(r'<body\b[^>]*>(.*?)</body>', html, re.S | re.I)
    body = m.group(1) if m else html

    for pat in STRIP_BLOCKS:
        body = pat.sub('', body)

    # Collapse whitespace so a reindent doesn't count as a content change.
    body = WS.sub(' ', body).strip()

    return hashlib.sha256(body.encode('utf-8')).hexdigest()[:16]

Two details matter more than they look:

Stripping shared blocks. My nav, footer, and CTA band are injected into every page by the build. If I hash them, every template edit becomes a site-wide content change — which is the exact problem I am trying to fix. They come out before hashing.

Collapsing whitespace. Otherwise a formatter run invalidates everything.

The state file

{
  "index.html":        {"hash": "9f2c1ab4d3e77a01", "lastmod": "2026-11-08"},
  "products.html":     {"hash": "3c81de2290aa4f57", "lastmod": "2026-11-14"},
  "articles/velvet-buyers-guide.html": {"hash": "77b0e4c15a2d9308", "lastmod": "2026-11-19"}
}

One entry per URL. lastmod only moves when hash moves.

The update step

import json
from datetime import date
from pathlib import Path

ROOT = Path('.')
STATE = Path('.lastmod_state.json')
SITEMAPS = ['sitemap-en.xml', 'sitemap-mirror.xml']

state = json.loads(STATE.read_text()) if STATE.exists() else {}
today = date.today().isoformat()
changed = []

for html in ROOT.rglob('*.html'):
    if any(p in html.parts for p in ('_bak', '.git', 'node_modules')):
        continue
    rel = html.relative_to(ROOT).as_posix()
    h = body_fingerprint(html)
    prev = state.get(rel)
    if prev is None:
        state[rel] = {'hash': h, 'lastmod': today}
        changed.append(rel)
    elif prev['hash'] != h:
        state[rel] = {'hash': h, 'lastmod': today}
        changed.append(rel)
    # else: hash unchanged -> lastmod stays exactly where it was

STATE.write_text(json.dumps(state, indent=1, sort_keys=True))
print('%d changed / %d tracked' % (len(changed), len(state)))

Then the sitemap generator reads lastmod from the state file instead of from mtime or now().

What actually happened

Before: every URL in the sitemap carried one of two dates (the last two deploy days). 277 entries, two distinct lastmod values.

After the first full backfill: the dates spread across the real publication history. Most pages kept their original date, a handful moved, and — critically — the next batch edit that touched 1,582 internal links moved zero lastmod values, because those edits lived in the nav and the CTA band, which are stripped before hashing.

That is the whole point. A link sweep is not a content change. Now the sitemap says so.

The tradeoff, stated plainly

You lose the appearance of a site that is "fresh every day." If someone looks at your sitemap and sees dates spread over three months, that looks less impressive than 1,287 pages all stamped yesterday.

But "all stamped yesterday" is not a signal crawlers reward — it is a signal that says ignore the ordering, we have no priorities. Spreading the dates is what lets the crawler spend its limited budget on the pages that changed, and skip the ones that did not.

Caveats

  • Backfill carefully. On the first run, every page gets today's date because there is no previous hash. Seed the state file from your real publication dates first, or you will reproduce the exact problem you are fixing.
  • Hash what the user sees, not the file. If your build injects a per-request nonce or a timestamp into the body, strip it too.
  • lastmod is a hint. Google has said it is used loosely. But "loosely used and honest" beats "loosely used and uniformly wrong."

Context: 1,287-page static catalogue, ten languages, Cloudflare Workers. The site is mujiatextile.com. The crawl-budget numbers in this post came from Search Console → Settings → Crawl stats.

📰 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.