Sub topic 14
Generating sitemaps from your site's data
This chapter assumes you know the sitemap XML structure (urlset, url, loc, lastmod), the 50,000-URL and 50 MB limits, and how sitemap index files work. You also need basic Python and SQL. The goal is to produce sitemaps from the same data that powers your pages, so the files stay correct without manual edits.
Why generate instead of hand-writing
A hand-maintained sitemap goes stale. New pages are missing, deleted pages stay listed, and lastmod values drift away from reality. A sitemap that lists URLs which redirect, return errors, or are blocked tells crawlers to distrust it.
Generation fixes this by making the sitemap a view of your data. The same database rows or content files that produce your pages also decide which URLs appear in the sitemap. When a page is published, unpublished, or edited, the next run reflects it.
Pick a source of truth
Generate the list from whatever already defines your pages:
| Site type | Source of URLs | Source of `lastmod` |
|---|---|---|
| Database-backed app | A query over published records | An `updated_at` column |
| Static site generator | The list of built pages or content files | Git commit date or front-matter date |
| Headless CMS | The CMS API's list of entries | The entry's modified timestamp |
| Mixed site | Union of the above, one sitemap file per section | Per section |
Do not build the list by crawling your own site. A crawl is slow, depends on the site being up, and finds only pages that are linked. The data is a more reliable and cheaper source.
Rules the generator must enforce
The generator is the right place to apply sitemap policy. A URL belongs in the file only if it passes every check below.
- Indexable. Exclude pages marked
noindex. Listing a URL you ask crawlers not to index sends contradictory signals. - Crawlable. Exclude URLs blocked by
robots.txt. A crawler can't fetch them, so listing them is pointless. - Canonical. List only the canonical version of each page. Leave out parameter variants, duplicates, and alternate URLs that point to a canonical elsewhere.
- Status 200. Exclude redirects, 404s, and drafts. Only final URLs that return 200 belong.
- Absolute and consistent. Use full URLs with the right scheme and host, for example
https://www.example.com/.... Don't mixhttpandhttps, orwwwand non-www. - Escaped. Percent-encode non-ASCII and reserved characters in paths, and let an XML library escape
&,<, and>. - Honest
lastmod. Use the time the page's content meaningfully changed, not the time the sitemap was built.
Rule 7 matters most for long-term trust. If every URL shows today's date on every run, crawlers learn the value carries no information and stop using it. Leave lastmod out for pages where you have no real modification date.
The pipeline
A complete generator
The script below uses an in-memory SQLite table as a stand-in for your data. It filters rows, percent-encodes paths, splits output into chunks, writes each chunk with ElementTree, and writes an index. The chunk size is a parameter so you can see the splitting with a tiny value.
import sqlite3
import xml.etree.ElementTree as ET
from pathlib import Path
from urllib.parse import quote
NS = "http://www.sitemaps.org/schemas/sitemap/0.9"
ET.register_namespace("", NS)
BASE = "https://www.example.com"
MAX_URLS = 50_000
MAX_BYTES = 50 * 1024 * 1024
def tag(name):
return f"{{{NS}}}{name}"
def chunked(rows, size):
batch = []
for row in rows:
batch.append(row)
if len(batch) == size:
yield batch
batch = []
if batch:
yield batch
def write_xml(root, path):
ET.ElementTree(root).write(path, encoding="utf-8", xml_declaration=True)
if Path(path).stat().st_size > MAX_BYTES:
raise ValueError(f"{path} exceeds the 50 MB uncompressed limit")
def write_sitemap(entries, path):
urlset = ET.Element(tag("urlset"))
for loc, lastmod in entries:
url = ET.SubElement(urlset, tag("url"))
ET.SubElement(url, tag("loc")).text = loc
if lastmod:
ET.SubElement(url, tag("lastmod")).text = lastmod
write_xml(urlset, path)
def write_index(entries, path):
index = ET.Element(tag("sitemapindex"))
for loc, lastmod in entries:
sm = ET.SubElement(index, tag("sitemap"))
ET.SubElement(sm, tag("loc")).text = loc
ET.SubElement(sm, tag("lastmod")).text = lastmod
write_xml(index, path)
def generate(conn, out_dir, chunk_size=MAX_URLS):
out = Path(out_dir)
out.mkdir(parents=True, exist_ok=True)
rows = conn.execute(
"SELECT path, updated_at FROM pages "
"WHERE status = 'published' AND noindex = 0 "
"ORDER BY path"
)
index_entries = []
for n, chunk in enumerate(chunked(rows, chunk_size), start=1):
entries = [(BASE + quote(path, safe="/"), updated) for path, updated in chunk]
name = f"sitemap-{n}.xml"
write_sitemap(entries, out / name)
newest = max(updated for _, updated in entries)
index_entries.append((f"{BASE}/{name}", newest))
if index_entries:
write_index(index_entries, out / "sitemap_index.xml")
return index_entries
if __name__ == "__main__":
conn = sqlite3.connect(":memory:")
conn.execute(
"CREATE TABLE pages (path TEXT, updated_at TEXT, status TEXT, noindex INTEGER)"
)
conn.executemany(
"INSERT INTO pages VALUES (?, ?, ?, ?)",
[
("/", "2026-11-01", "published", 0),
("/about", "2026-09-12", "published", 0),
("/blog/first-post", "2026-10-15", "published", 0),
("/blog/café menu", "2026-11-20", "published", 0),
("/blog/draft", "2026-11-25", "draft", 0),
("/thank-you", "2026-08-01", "published", 1),
],
)
for loc, lastmod in generate(conn, "public", chunk_size=2):
print(loc, lastmod)Running it prints two sitemap entries, because four rows pass the filter and the chunk size is 2. The draft and the noindex page are never written. The path /blog/café menu becomes /blog/caf%C3%A9%20menu.
A few details are worth noting:
- The query streams rows through
chunked, so a site with millions of URLs never loads everything into memory. ORDER BY pathgives stable output. Stable ordering keeps file diffs small and makes caching and debugging easier.- The index
lastmodis the newestlastmodin that chunk, which is honest and needs no extra bookkeeping. Comparing ISO date strings works as long as every value uses the same format. If you mix dates and datetimes, normalize them before taking the maximum. - Each file's size is checked after writing, because the 50 MB limit applies to the uncompressed file.
Limits in practice
The limit of 50,000 URLs is the one you usually hit first, but long URLs or many extension tags (images, hreflang alternates) can push a file past 50 MB well before 50,000 entries. If the size check raises an error, lower the chunk size. A chunk size of 10,000 to 40,000 is a sensible default for sites with heavy extensions.
You can serve files gzip-compressed (sitemap-1.xml.gz). The limits still apply to the uncompressed size, so compression saves bandwidth but does not raise the ceiling.
Splitting by content type, such as sitemap-blog.xml and sitemap-products.xml, is often better than splitting by count alone. It lets you see per-section indexing numbers in search console reports and regenerate only the section that changed.
Running it on a schedule
Choose the trigger that matches how your content changes:
- At build time for static sites. The sitemap is a build artifact deployed with the pages, so it can never disagree with them.
- On publish events for CMS-driven sites. Regenerate the affected section when an editor publishes or unpublishes.
- On a schedule (cron, a job runner) for large dynamic sites. Hourly or daily is typical.
Write to a temporary file and rename it into place, so a crawler never fetches a half-written file. After generation, make sure the index is reachable and referenced from robots.txt:
Sitemap: https://www.example.com/sitemap_index.xmlSubmitting the index in each search engine's webmaster tool is optional once robots.txt references it, but it gives you per-file processing reports.
Common errors
- Sitemap lists redirected URLs. The data stores an old path while the router redirects it. Filter on the final canonical path, not on the raw database field.
- Wrong host or scheme. A hard-coded
http://or staging host reaches production. ReadBASEfrom environment configuration and assert it starts withhttps://. - Unescaped characters. Building XML with string concatenation breaks on
&in query strings. Use an XML library. - Fake
lastmod. Usingdatetime.now()for every URL. Use stored modification times or omit the field. - Empty or partial output after a failure. Generate to a temporary directory and move it into place only when the whole run succeeds.
- Stale index. Pages are regenerated but the index still points at deleted chunk files. Always rewrite the index in the same run, and remove chunk files from earlier runs that no longer exist.
Exercise
Your generator produces a sitemap in which every lastmod equals the time the script ran. Pages are rarely edited. What problem does this cause, and how would you fix it in the generator?
Show answer
Crawlers compare lastmod with what they have already seen, and a value that changes on every run without real edits is wrong. Over time they learn to ignore the field for your site, so genuine updates are also discovered more slowly. Fix it by reading each page's real modification time from the data (for example an updated_at column or the Git commit date) and writing that. If no reliable date exists for a page, omit lastmod for it.
Exercise
A site has 120,000 indexable URLs. Using the generator above with the default chunk_size, how many sitemap files and index entries are produced, and which setting would you lower if a file still exceeded 50 MB?
Show answer
Three sitemap files (50,000 + 50,000 + 20,000 URLs) and three entries in sitemap_index.xml. If a file exceeds 50 MB uncompressed, lower chunk_size so each file holds fewer URLs, which also produces more files and more index entries.