# Monitor canonicals and sitemaps

- Check 46.04 · Automation and quality control · Complementary
- Source: https://checklist-seo-geo.com/en/automation-quality-control/monitor-canonicals-sitemaps
- Automatically check that your sitemaps list only indexable, canonical URLs returning 200, and get alerted when a canonical or a sitemap changes.
- Updated on 2026-11-25
- Licence: CC BY 4.0. Credit “Checklist SEO & GEO” with a link to https://checklist-seo-geo.com/en/automation-quality-control/monitor-canonicals-sitemaps.
- Plugin checklist-seo-geo: 1.3.1 · https://github.com/maximegaul/checklist-seo-geo

## In short

The sitemap tells search engines which URLs you want indexed; the canonical tag says, page by page, which address represents the content. Both must tell the same story. Monitoring means checking every day that the sitemaps respond, that their volume does not collapse, and that a sample of their URLs returns 200, with no noindex, and with a canonical pointing to itself. Once this check is done, any divergence between sitemap, canonical and the actual state of the page triggers an alert.

## Why it matters

Google describes the canonical tag as a strong signal and the sitemap as a weak signal for choosing the canonical URL, and recommends not designating different URLs as canonical through different methods. When the sitemap lists a URL whose canonical points elsewhere, the signals contradict each other: Google chooses for itself, and not necessarily the URL you wanted.

These inconsistencies rarely come from a decision. They come from the code:

- a template that writes the canonical with the wrong protocol, without the trailing slash or with the URL's parameters;
- pagination or a filter that returns the first page's canonical for every page;
- a sitemap generator that keeps listing deleted products, redirected pages or noindex pages;
- a scheduled sitemap generation task that fails, leaving a file frozen for weeks;
- a plugin that adds a second canonical tag, different from the first.

The crawlers of generative engines rely on the same signals to know which version of a page to read and cite. A broken canonical scatters your signals across several URLs.

## What it improves

- **Indexing**: the URLs you want indexed are the ones Google selects as canonical.
- **Crawling**: crawlers do not waste time on redirected, failing or excluded URLs listed in the sitemaps.
- **Signal consolidation**: links and usage data concentrate on a single URL per piece of content.
- **Report reliability**: the Search Console indexing reports, filtered on submitted pages, become readable.
- **Rankings**: indirect effect, through better consolidation; nothing guaranteed.

## How to check

Count the URLs in the sitemap and test one:

```bash
curl -s https://example.com/sitemap.xml | grep -c "<loc>"
curl -s https://example.com/categorie/chaussures/ | grep -ioE '<link[^>]+rel=["'"'"']?canonical[^>]*>'
```

Expected result: the sitemap responds, the number of URLs is consistent with the size of the site, and the canonical of each tested page is its exact absolute URL: `https://example.com/categorie/chaussures/`.

In Search Console:

- the [Sitemaps report](https://search.google.com/search-console/sitemaps) shows the status “Success”, a recent last read date and a stable number of discovered URLs;
- the [Page indexing report](https://search.google.com/search-console/index), filtered on “All submitted pages”, should not show a large volume for “Page with redirect”, “Alternate page with proper canonical tag” or “Duplicate, Google chose different canonical than user”.

## How to implement

### Before you start

Set the rules the check will verify. They follow from the checks [include only indexable canonical URLs returning HTTP 200](https://checklist-seo-geo.com/en/crawling/include-only-indexable-canonical-urls-returning-http-200) and [align canonicals, sitemap and internal links](https://checklist-seo-geo.com/en/indexing-canonicalization/align-canonicals-sitemap-internal-links):

| Check | Rule | Severity |
|---|---|---|
| Sitemap or sitemap index | Returns 200, valid XML | Critical |
| URL volume | No drop of more than 10% from one day to the next (convention, to be adjusted) | Critical |
| Listed URLs | Return 200, with no redirect | High |
| Directives | No listed URL with noindex | High |
| Canonical | Present, unique, absolute, identical to the listed URL | High |
| `lastmod` | Never in the future | Medium |
| Duplicates | No URL listed twice | Medium |

The protocol limits still apply: 50,000 URLs and 50 MB uncompressed per file, 50,000 sitemaps per index. See [split large sitemaps](https://checklist-seo-geo.com/en/crawling/split-large-sitemaps).

### The check script

This Python script uses only the standard library. It reads the sitemap or sitemap index (gzip-compressed files included), checks the volume against the previous run, then tests a random sample of URLs: HTTP status code without following redirects, robots directives, and the canonical declared in the HTML or in the `Link` header. Save it as `/srv/controles/controle-sitemaps.py`:

```python
#!/usr/bin/env python3
"""Checks sitemaps: each URL must return 200, with no noindex, and with a canonical pointing to itself."""
import datetime, gzip, os, random, re, sys, time
import xml.etree.ElementTree as ET
from html.parser import HTMLParser
from urllib.error import HTTPError, URLError
from urllib.parse import urljoin
from urllib.request import HTTPRedirectHandler, Request, build_opener

SITEMAP, SAMPLE, STATE = sys.argv[1], int(sys.argv[2]), sys.argv[3]
NS = "{http://www.sitemaps.org/schemas/sitemap/0.9}"
UA = "Mozilla/5.0 (compatible; controle-sitemaps/1.0)"


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, *args):
        return None


class Head(HTMLParser):
    def __init__(self):
        super().__init__()
        self.canonicals, self.robots = [], ""

    def handle_starttag(self, tag, attrs):
        a = dict(attrs)
        if tag == "link" and "canonical" in (a.get("rel") or "").lower().split():
            self.canonicals.append(a.get("href") or "")
        elif tag == "meta" and (a.get("name") or "").lower() in ("robots", "googlebot"):
            self.robots += (a.get("content") or "").lower()


opener = build_opener(NoRedirect)


def fetch(url):
    try:
        return opener.open(Request(url, headers={"User-Agent": UA}), timeout=20)
    except HTTPError as err:
        return err


def sitemap_urls(url, alerts):
    resp = fetch(url)
    if resp.status != 200:
        alerts.append(f"SITEMAP {resp.status} {url}")
        return []
    body = resp.read()
    if body[:2] == b"\x1f\x8b":
        body = gzip.decompress(body)
    root = ET.fromstring(body)
    if root.tag == f"{NS}sitemapindex":
        return [u for loc in root.iter(f"{NS}loc") for u in sitemap_urls(loc.text.strip(), alerts)]
    today = datetime.date.today().isoformat()
    for lastmod in root.iter(f"{NS}lastmod"):
        if lastmod.text.strip()[:10] > today:
            alerts.append(f"FUTURE LASTMOD {lastmod.text.strip()} in {url}")
            break
    return [loc.text.strip() for loc in root.iter(f"{NS}loc")]


alerts = []
urls = sitemap_urls(SITEMAP, alerts)
if len(urls) != len(set(urls)):
    alerts.append(f"DUPLICATES {len(urls) - len(set(urls))} duplicate URLs")

previous = int(open(STATE).read()) if os.path.exists(STATE) else 0
if previous and len(urls) < 0.9 * previous:
    alerts.append(f"VOLUME {previous} -> {len(urls)} URLs in the sitemaps")
with open(STATE, "w") as f:
    f.write(str(len(urls)))

for url in random.sample(urls, min(SAMPLE, len(urls))):
    try:
        resp = fetch(url)
    except URLError as err:
        alerts.append(f"ERROR {url}: {err.reason}")
        continue
    if resp.status != 200:
        alerts.append(f"{resp.status} {url} -> {resp.headers.get('Location', '')}")
        continue
    head = Head()
    head.feed(resp.read().decode("utf-8", "replace"))
    robots = head.robots + (resp.headers.get("X-Robots-Tag") or "").lower()
    header_canonical = re.search(r'<([^>]+)>;\s*rel="?canonical', resp.headers.get("Link") or "")
    canonicals = head.canonicals + ([header_canonical.group(1)] if header_canonical else [])
    if "noindex" in robots or "none" in robots:
        alerts.append(f"NOINDEX {url}")
    if not canonicals:
        alerts.append(f"NO CANONICAL {url}")
    elif len(set(canonicals)) > 1:
        alerts.append(f"MULTIPLE CANONICALS {url}: {' | '.join(set(canonicals))}")
    elif urljoin(url, canonicals[0]) != url:
        alerts.append(f"CANONICAL ELSEWHERE {url} -> {canonicals[0]}")
    time.sleep(0.5)

print(f"{len(urls)} URLs in the sitemaps, {min(SAMPLE, len(urls))} tested, {len(alerts)} alert(s).")
print("\n".join(alerts))
sys.exit(1 if alerts else 0)
```

Arguments: URL of the sitemap or index, sample size, state file that stores the volume. The random sample changes with each run: over a month, 200 URLs tested per day cover 6,000 different URLs without loading the server. For a site of a few hundred pages, test them all.

The canonical comparison is strict: a difference of one trailing slash or one `www` is reported. This is intentional, as these differences are precisely the ones that create duplicates. The script reads the initial HTML; if the canonical is injected by JavaScript, see [check title, description and canonical after rendering](https://checklist-seo-geo.com/en/javascript-html-rendering/check-title-description-canonical-after-rendering).

Schedule it every night with cron (`crontab -e`):

```txt
30 4 * * * cd /srv/controles && python3 controle-sitemaps.py https://example.com/sitemap.xml 200 /srv/controles/volume-sitemap.txt > /tmp/sitemaps.log 2>&1 || mail -s "Sitemaps / canonicals: alert" seo@example.com < /tmp/sitemaps.log
```

Schedule it after the time the sitemap is generated, to check that day's file. Without a server, use GitHub Actions following the model in [schedule automated crawls](https://checklist-seo-geo.com/en/automation-quality-control/schedule-automated-crawls).

### Compare with the canonical selected by Google

The script checks the canonical you declare. Google may select a different one. To find out for your key pages:

- **URL Inspection**: the indexing section shows “User-declared canonical” and “Google-selected canonical”. The manual method is detailed in [compare declared and Google-selected canonicals](https://checklist-seo-geo.com/en/indexing-canonicalization/compare-declared-google-selected-canonicals).
- **URL Inspection API**: it returns the same information programmatically, within a limit of 2,000 requests per day and 600 per minute for a property. A weekly check of your 100 to 500 most important pages fits easily within this quota.
- **Page indexing report**: track every week the number of submitted URLs classified as “Duplicate, Google chose different canonical than user”. A rise signals a template whose canonical is not trusted.

### With Search Console and Bing Webmaster Tools

- **Sitemaps**: in the [Sitemaps report](https://search.google.com/search-console/sitemaps), a read error appears in the status column. Search Console also emails owners and users when new indexing issues arise.
- **Bing**: the [Sitemaps report in Bing Webmaster Tools](https://www.bing.com/webmasters/sitemaps) shows for each file its status, last read date and number of discovered URLs.
- **Indexing by sitemap**: submit separate sitemaps by content type (pages, categories, products, articles). The Page indexing report can then be filtered on each sitemap, which immediately pinpoints the template at fault.

### With a scheduled crawl

A crawl covers what the script does not see: indexable URLs missing from the sitemaps and the canonicals of unlisted pages.

- **Screaming Frog**: in `Configuration > Spider > Crawl`, turn on crawling of linked XML sitemaps and enter their address. The `Sitemaps` tab then lists non-indexable URLs present in a sitemap and indexable URLs missing from the sitemaps; the `Canonicals` tab lists canonicals that are missing, multiple or pointing to a non-indexable page. Export these filters in the scheduled crawl.
- **Semrush, Ahrefs, Sitebulb**: their audits report the same issues (sitemap URLs returning errors or redirected, broken canonicals) and compare successive audits.

### WordPress

Versions: WordPress 6.4 and later.

WordPress generates a native sitemap (`/wp-sitemap.xml`) and a canonical on individual content. SEO plugins replace them: Yoast SEO publishes `/sitemap_index.xml`, and so does Rank Math. Points to monitor:

- **A single generator**: two competing sitemaps (native and plugin) contradict each other. Check which one is declared in robots.txt and submitted to Search Console.
- **After a plugin update**, run the check again: the settings by content type decide what goes into the sitemap.
- **Cache**: a caching plugin or a CDN can serve an outdated sitemap. Exclude sitemap URLs from the page cache, or purge them at each publication.

### Shopify

Versions: Shopify, all plans, November 2026.

Shopify generates `/sitemap.xml` automatically and you cannot edit it. The canonical comes from the theme, usually `<link rel="canonical" href="{{ canonical_url }}">` in `layout/theme.liquid`. Above all, monitor theme changes and apps that inject a second canonical: the script reports them as “MULTIPLE CANONICALS”.

### Laravel

Versions: Laravel 11 to 13.

If the sitemap is generated by a scheduled task (for example with spatie/laravel-sitemap), report its success to a heartbeat service, as described in [monitor uptime and alerts](https://checklist-seo-geo.com/en/security-infrastructure/monitor-uptime-alerts). A feature test protects a template's canonical:

```php
it('declares an absolute canonical pointing to the page itself', function () {
    $response = $this->get('/categorie/chaussures?tri=prix');

    $response->assertOk()
        ->assertSee('<link rel="canonical" href="'.url('/categorie/chaussures').'">', false);
});
```

The test checks that sorting parameters do not get into the canonical. Adapt the expected string to your template's exact markup.

### Next.js

Versions: Next.js 15 and 16 (App Router).

The canonical is declared in `metadata.alternates.canonical`, resolved against `metadataBase`, and the sitemap in `app/sitemap.ts`. Two common pitfalls: `metadataBase` pointing to a preview domain, and a canonical defined in the root `layout`, inherited by every page, which makes the homepage the canonical of the whole site. The script detects both (“CANONICAL ELSEWHERE”).

### Cloudflare

Versions: Cloudflare dashboard, all plans, November 2026.

If a cache rule caches the sitemap for a long time, search engines read an outdated version. Limit the cache duration of sitemap files in the [cache rules](https://dash.cloudflare.com/?to=/:account/:zone/caching/cache-rules), or purge them after each generation.

## Common mistakes

- **Listing redirected or noindex URLs in the sitemap**: contradictory signals, and unreadable indexing reports.
- **Relative or protocol-less canonical**: Google recommends absolute URLs; a relative canonical breaks at the first change of domain or staging environment.
- **Canonical inherited from a parent template**: every page declares the homepage as canonical.
- **Two canonicals on the same page**, often one from the theme and the other from a plugin: Google may ignore both.
- **Frozen sitemap**: generation failed, and the file is still served with old URLs. Monitor the task, not just the file.
- **Blocking the sitemap or canonical pages in robots.txt**: Google recommends not using robots.txt for canonicalization.
- **`lastmod` updated at every generation**: a date that changes without any real change to the content loses its value as a signal.

## Frequently asked questions

### Should canonicalized URLs be included in the sitemap?

No. A sitemap should list only canonical, indexable URLs that return 200. A URL whose canonical points to another page sends two contradictory signals to Google, which then chooses for itself which version to index. List the canonical page, remove the variants (sorting parameters, canonicalized paginated versions, old URLs) and regularly check that the generator follows this rule.

### Why does Google choose a different canonical from mine?

Google treats the canonical tag as a strong signal, not an obligation. It selects another URL when signals contradict each other: a sitemap listing a variant, internal links to another version, redirects, nearly identical content across several pages. The URL Inspection tool in Search Console shows the declared canonical and the one Google selected. Align sitemap, internal links and canonical on the same address.

### How often should you check sitemaps and canonicals?

Check sitemaps and canonicals once a day, after the sitemap is generated, and after each deployment that touches a template. On a large site, a random sample of a few hundred URLs a day is enough to cover everything within a few weeks without loading the server. Add a weekly or monthly scheduled crawl, which also sees pages missing from the sitemaps.

### Is the Search Console Sitemaps report enough?

The Search Console Sitemaps report shows whether Google could read your files and how many URLs it discovered in them, but it does not check the state of each URL or the consistency of canonicals. Cross-reference it with the Page indexing report filtered on submitted pages, and add a daily automated check, which detects a regression the same day rather than after the next crawl.

## Resources

- [Google Search Central: specify a canonical URL](https://developers.google.com/search/docs/crawling-indexing/consolidate-duplicate-urls)
- [Google Search Central: build and submit a sitemap](https://developers.google.com/search/docs/crawling-indexing/sitemaps/build-sitemap)
- [Sitemaps protocol](https://www.sitemaps.org/protocol.html)
- [Google: URL Inspection API and quotas](https://developers.google.com/webmaster-tools/limits)
- [Search Console Help: Sitemaps report](https://support.google.com/webmasters/answer/7451001)
- [Next.js: metadata alternates and metadataBase](https://nextjs.org/docs/app/api-reference/functions/generate-metadata)

Next steps: [monitor titles and structured data](https://checklist-seo-geo.com/en/automation-quality-control/monitor-titles-structured-data), [create deindexing alerts](https://checklist-seo-geo.com/en/automation-quality-control/create-deindexing-alerts) and [exclude redirects, errors and noindex pages](https://checklist-seo-geo.com/en/crawling/exclude-redirects-errors-noindex-pages).
