Check 04.14 · Indexing and canonicalization

Align canonicals, sitemap and internal links

Make the canonical, the sitemap and internal links point to the same URL: audit with a crawler or a free script, then fix it in your CMS and framework.

Priority
Critical
Difficulty
Intermediate
Estimated time
2 h to 1 day
Free, no account: your progress is saved in this browser.

Ask an AI to check this point on your site

Opens the assistant with a ready-made question: this check, its goal and your site URL.

For Gemini, Copilot or another assistant, copy the question. The link opens the chosen service directly: nothing goes through this site.

In short

Three signals tell search engines which URL represents a page: the canonical tag, the address listed in the XML sitemap and the target of internal links. Aligning them means making all three point to exactly the same URL, character for character: same protocol, same host, same trailing slash, no parameters. The expected result: a sitemap that contains only self-referencing URLs returning 200, and internal links that point neither to a redirect nor to a page canonicalized elsewhere.

Why it matters

Google chooses the canonical version of a group of duplicates by weighing several signals. Its documentation ranks three of them by strength: redirects and the canonical tag are strong signals, presence in a sitemap is a weak signal, and these methods reinforce each other when combined. It adds two direct instructions: do not specify different canonical URLs for the same page using different methods (for example a sitemap that contradicts the canonical), and point internal links to the canonical URL rather than to a duplicate.

When the signals diverge, three things happen:

  • Google decides for you: it may select the URL your links cite most, even if your canonical says otherwise. The indexing report then shows "Duplicate, Google chose different canonical than user".
  • Crawling gets scattered: every link to http://, to a URL without a trailing slash that redirects or to a parameterized variant costs one extra request.
  • The sitemap loses its value: full of redirected, canonicalized or noindex URLs, it stops being a reliable list of your reference pages.

What it improves

  • Choice of canonical Your preference is followed more often, because every signal confirms it.
  • Crawling Fewer redirects and duplicates crawled; the effect is noticeable mainly on large sites.
  • Indexing reports Fewer "Page with redirect" and "Duplicate" entries among submitted pages.
  • Load time A link that avoids a redirect saves the visitor a round trip.
  • AI answers Indirect. Engines cite the URL selected in their index; consistent signals prevent a variant from being shown. No practice guarantees a citation.

How to check

Quick check on one page:

URL="https://example.com/produits/sencha-ariake/"
curl -s "$URL" | grep -oiE '<link[^>]*rel="?canonical"?[^>]*>'
curl -s https://example.com/sitemap.xml | grep -c "<loc>$URL</loc>"
curl -s https://example.com/thes/the-vert/ | grep -oE 'href="[^"]*sencha-ariake[^"]*"' | sort | uniq -c

Expected result: the canonical is $URL, the sitemap contains it once, and every link from the category points to $URL in the same form.

In Search Console, open the Page indexing report with the "All submitted pages" filter: "Page with redirect", "Alternate page with proper canonical tag" or "Duplicate…" reasons on submitted URLs point to a misaligned sitemap. The Sitemaps report shows the number of discovered URLs for each sitemap.

How to implement

Step 1 — Settle on a single URL form

Before aligning, decide on the reference form: https, with or without www, trailing slash or not, lowercase, no tracking parameters. Every other form redirects with a 301 to it. See standardize HTTP/HTTPS and www/non-www (opens in a new tab), standardize letter case and trailing slashes (opens in a new tab) and check canonicals and absolute URLs (opens in a new tab).

Step 2 — Cross-check the three sources with a crawler

In Screaming Frog:

  1. Configuration > Spider > Crawl: tick "Crawl Linked XML Sitemaps" and add the address of your sitemaps.
  2. Start the crawl from the homepage, then run Crawl Analysis > Start at the end.
  3. Sitemaps tab: "Non-Indexable URLs in Sitemap" (sitemap URLs that redirect, return an error, are noindex or are canonicalized), "URLs Not In Sitemap" (indexable pages missing from the sitemap), "Orphan URLs" (URLs found only in the sitemap, with no internal link).
  4. Canonicals tab: "Canonicalised" (pages that designate another URL: are they linked?), "Unlinked" (canonical URLs mentioned only by the canonical tag).
  5. Response Codes tab: filter on internal redirects, then export the inlinks of these URLs to find out which pages cite them.

Oncrawl, Botify, or the Semrush and Ahrefs site audits offer equivalent checks.

Step 2b — Without a paid tool

This dependency-free Python script crawls the site from the homepage (up to 500 pages), reads the sitemap and reports every misalignment. Save it as aligner.py, replace example.com, then run python3 aligner.py > alignement.tsv:

#!/usr/bin/env python3
import re
import time
import urllib.error
import urllib.parse
import urllib.request
from collections import deque
from html.parser import HTMLParser

SITE = "https://example.com"
SITEMAP = f"{SITE}/sitemap.xml"
LIMIT = 500


class PageParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.links, self.canonicals, self.noindex = [], [], False

    def handle_starttag(self, tag, attrs):
        a = {name: value or "" for name, value in attrs}

        if tag == "a" and a.get("href"):
            self.links.append(a["href"])

        if tag == "link" and "canonical" in a.get("rel", "").lower().split():
            self.canonicals.append(a.get("href", ""))

        if tag == "meta" and a.get("name", "").lower() == "robots" and "noindex" in a.get("content", "").lower():
            self.noindex = True


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        return None


opener = urllib.request.build_opener(NoRedirect)


def fetch(url):
    request = urllib.request.Request(url, headers={"User-Agent": "audit-alignement/1.0"})
    time.sleep(0.2)

    try:
        with opener.open(request, timeout=15) as response:
            return response.status, response.headers.get("Content-Type", ""), response.read().decode("utf-8", "replace")
    except urllib.error.HTTPError as error:
        return error.code, "", ""
    except urllib.error.URLError:
        return 0, "", ""


def clean(base, href):
    return urllib.parse.urldefrag(urllib.parse.urljoin(base, href.strip()))[0]


def sitemap_urls(url):
    _, _, body = fetch(url)
    locs = re.findall(r"<loc>\s*([^<\s]+)\s*</loc>", body)

    if "<sitemapindex" in body:
        return {page for child in locs for page in sitemap_urls(child)}

    return set(locs)


def inspect(url):
    status, content_type, body = fetch(url)
    parser = PageParser()

    if "html" in content_type:
        parser.feed(body)

    canonical = clean(url, parser.canonicals[0]) if parser.canonicals else ""

    return {"status": status, "canonical": canonical, "noindex": parser.noindex, "count": len(parser.canonicals)}, parser.links


def report(kind, url, detail=""):
    print(f"{kind}\t{url}\t{detail}")


in_sitemap = sitemap_urls(SITEMAP)
host = urllib.parse.urlparse(SITE).netloc
pages, inlinks = {}, {}
queue, seen = deque([f"{SITE}/"]), {f"{SITE}/"}

while queue and len(pages) < LIMIT:
    url = queue.popleft()
    pages[url], links = inspect(url)

    for href in links:
        target = clean(url, href)

        if urllib.parse.urlparse(target).netloc != host:
            continue

        inlinks.setdefault(target, url)

        if target not in seen:
            seen.add(target)
            queue.append(target)

crawl_complete = not queue

for url in in_sitemap - pages.keys():
    pages[url], _ = inspect(url)

for url in sorted(in_sitemap):
    page = pages[url]

    if page["status"] != 200:
        report("SITEMAP_NON_200", url, page["status"])
    elif page["noindex"]:
        report("SITEMAP_NOINDEX", url)
    elif page["canonical"] != url:
        report("SITEMAP_CANONICAL_ELSEWHERE", url, page["canonical"])

    if crawl_complete and url not in inlinks and url != f"{SITE}/":
        report("SITEMAP_NO_INTERNAL_LINK", url)

for target, source in sorted(inlinks.items()):
    page = pages.get(target)

    if page is None:
        continue

    if page["status"] in (301, 302, 307, 308):
        report("LINK_TO_REDIRECT", target, f"from {source}")
    elif page["status"] >= 400:
        report("BROKEN_LINK", target, f"from {source}")
    elif page["canonical"] and page["canonical"] != target:
        report("LINK_TO_NON_CANONICAL", target, f"from {source}, canonical {page['canonical']}")

for url, page in sorted(pages.items()):
    if page["count"] > 1:
        report("MULTIPLE_CANONICALS", url)

    if page["status"] == 200 and not page["noindex"] and page["canonical"] == url and url not in in_sitemap:
        report("CANONICAL_NOT_IN_SITEMAP", url)

The script ignores JavaScript: on a client-side rendered site, use a crawler with rendering. Open the TSV file in a spreadsheet and filter on the first column.

Step 3 — Decide on each discrepancy

Discrepancy found Fix
Sitemap URL that redirects Replace it with the final URL in the sitemap generator
Sitemap URL returning 404, 410 or noindex Remove it from the sitemap. See exclude redirects, errors and noindex pages (opens in a new tab)
Sitemap URL whose canonical designates another page Put the canonical URL in the sitemap, or fix the canonical if that is what is wrong
Indexable canonical page missing from the sitemap Add it, or question whether it should be indexed
Internal link to a redirect Replace the target with the final URL. See fix links to redirects or non-canonical URLs (opens in a new tab)
Internal link to a canonicalized URL Point to the canonical URL, unless it is a filter or sort deliberately linked for visitors
Sitemap URL with no internal link Link to it from a relevant page. See detect orphan pages (opens in a new tab)
Several canonical tags Keep a single source

hreflang annotations, structured data (url, @id) and the og:url tag must also cite the canonical URL: Google asks you not to list an http:// version in the sitemap or in hreflang annotations.

Tip: fix things at the source, not in a spreadsheet. A list of 300 links to correct by hand builds up again with the next article; a function that builds the URL in one place for the canonical, the sitemap and the links solves the problem for good.

Step 4 — Monitor

Rerun the crawl or the script after every major release, and every month on a site that publishes often. Add three indicators to your tracking: non-self-referencing sitemap URLs, internal links to redirects, canonical pages missing from the sitemap. Automating them is covered in monitor canonicals and sitemaps (opens in a new tab).

The following sections give the fixes at the source, platform by platform.

WordPress

Versions WordPress 6.4 to 7.1, WP-CLI 2.x; sitemap from core, Yoast SEO 20 and later, or Rank Math 1.0.x.

  • Links produced by WordPress (the_permalink(), page menus, post lists) follow the permalinks and are aligned. Discrepancies come from links typed by hand in the content and from custom links in menus: old domains, http://, missing trailing slash.
  • To replace an old URL form in bulk, use WP-CLI, after backing up the database:
wp search-replace 'http://example.com' 'https://example.com' --dry-run
wp search-replace 'http://example.com' 'https://example.com' --skip-columns=guid
  • Sitemap: use the one from Yoast SEO, Rank Math or core (/wp-sitemap.xml), only one at a time. Check that it excludes noindex content and content whose canonical designates another page; the behavior depends on the plugin and its version.
  • A redirection plugin that logs 404s and redirects helps you spot the internal links to fix.

Shopify

Versions Online Store 2.0 themes (Dawn and derived themes), all Shopify plans, November 2026.

The sitemap (/sitemap.xml) lists products under /products/… and a product's canonical points to that same address. The misalignment comes from the theme: some build the links in collection grids with the within filter, which produces /collections/thes-verts/products/sencha-ariake. Shopify itself notes that these two URLs carry the same content. In the grid sections (snippets/card-product.liquid or equivalent), replace:

<a href="{{ product.url | within: collection }}">{{ product.title }}</a>

with:

<a href="{{ product.url }}">{{ product.title }}</a>

The product breadcrumb can still show the originating collection without changing the URL.

PrestaShop

Versions PrestaShop 8 and 9, Google sitemap module (gsitemap).

The Google sitemap module generates the file from the back office (Modules > Module Manager, sitemap module, then generate). Regenerate it after every change to the URL structure in Shop Parameters > Traffic & SEO, and check that links in product lists and the canonical of product pages use the same form, with or without the combination ID.

Magento

Versions Magento Open Source and Adobe Commerce 2.4.6 to 2.4.9.

In Stores > Configuration > Catalog > Catalog > Search Engine Optimization, with "Use Categories Path for Product URLs" set to "No", links to products use the short URL, the one the product canonical points to. Adobe notes that the category path creates several URLs for the same page. The sitemap is configured in Stores > Configuration > Catalog > XML Sitemap and generated in Marketing > SEO & Search > Site Map.

Laravel

Versions Laravel 11 to 13; spatie/laravel-sitemap 7.4 (PHP 8.2 and later) or 8.x (PHP 8.4 and later).

Centralize URL building in the model and use it everywhere:

class Product extends Model
{
    public function canonicalUrl(): string
    {
        return route('products.show', ['product' => $this->slug]);
    }
}

In the view, <link rel="canonical" href="{{ $product->canonicalUrl() }}"> and <a href="{{ $product->canonicalUrl() }}">. For the sitemap, with spatie/laravel-sitemap:

use App\Models\Product;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;

$sitemap = Sitemap::create();

Product::query()->where('is_published', true)->each(function (Product $product) use ($sitemap): void {
    $sitemap->add(Url::create($product->canonicalUrl())->setLastModificationDate($product->updated_at));
});

$sitemap->writeToFile(public_path('sitemap.xml'));

Put this code in a scheduled Artisan command, for example generate-sitemap.

Next.js

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

A single module builds the paths, used by the metadata, the links and app/sitemap.js:

// lib/urls.js
export const SITE_URL = 'https://example.com';
export const productPath = (slug) => `/produits/${slug}`;

// app/produits/[slug]/page.js
import { productPath } from '@/lib/urls';

export async function generateMetadata({ params }) {
  const { slug } = await params;

  return { alternates: { canonical: productPath(slug) } };
}

// app/sitemap.js
import { SITE_URL, productPath } from '@/lib/urls';

export default async function sitemap() {
  const products = await getPublishedProducts();

  return products.map((product) => ({
    url: `${SITE_URL}${productPath(product.slug)}`,
    lastModified: product.updatedAt,
  }));
}

In components, use <Link href={productPath(product.slug)}>. Respect the trailingSlash setting of next.config.js (or next.config.ts) in productPath, otherwise every link triggers a redirect.

Astro

Versions Astro 5 to 7, @astrojs/sitemap integration.

With @astrojs/sitemap, the sitemap is generated from the pages and the site value in astro.config.mjs. Set trailingSlash ('always' or 'never') in the same configuration and write internal links in that form, so that links, canonical and sitemap match.

Common mistakes

  • Sitemap generated from the database, links from the theme: two URL builders that diverge at the first change.
  • Inconsistent trailing slash: the canonical with a final /, the links without, and a 301 redirect between the two.
  • Hard-coded absolute links in content: old domains or http:// left in articles after a migration.
  • Products linked through the collection or category path while the canonical designates the short URL.
  • Sitemap listing parameterized or paginated URLs that are canonicalized to another page.
  • Two competing sitemaps: WordPress core's and a plugin's, or a forgotten old static file.
  • Fixing the sitemap without fixing the links: Google keeps seeing the variant cited throughout the site.

Frequently asked questions

Should sitemap URLs be identical to the canonical?

Yes. Google treats every URL in a sitemap as a suggested canonical, and asks you not to specify different canonical URLs for the same page using different methods. Every address in the sitemap must therefore be exactly the one the page declares in its canonical tag, character for character: same protocol, same host, same trailing slash, no parameters. A URL that redirects, is noindex or is canonicalized elsewhere has no place in the sitemap.

Updated on

Topic checklist (PDF)

And now?

In the “Indexing and canonicalization” topic

  1. Check that the homepage is indexed
  2. Check strategic pages
  3. Check meta robots and X-Robots-Tag
  4. Remove accidental noindex tags
  5. Keep customer accounts and carts out of the index
  6. Handle internal search results with no SEO value
  7. Protect staging and private data with authentication
  8. Analyze pages discovered but not indexed
  9. Analyze pages crawled but not indexed
  10. Fix abnormal exclusions
  11. Fix soft 404s
  12. Check canonicals and absolute URLs
  13. Use self-referencing canonicals where relevant
  14. Align canonicals, sitemap and internal links
  15. Identify and consolidate duplicates
  16. Control parameterized URLs
  17. Standardize HTTP/HTTPS and www/non-www
  18. Compare declared and Google-selected canonicals
  19. Check Bing indexing
  20. Monitor indexing reports