# Align canonicals, sitemap and internal links

- Check 04.14 · Indexing and canonicalization · Critical
- Source: https://checklist-seo-geo.com/en/indexing-canonicalization/align-canonicals-sitemap-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.
- Updated on 2026-11-25
- Licence: CC BY 4.0. Credit “Checklist SEO & GEO” with a link to https://checklist-seo-geo.com/en/indexing-canonicalization/align-canonicals-sitemap-internal-links.
- Plugin checklist-seo-geo: 1.3.1 · https://github.com/maximegaul/checklist-seo-geo

## 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:

```bash
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](https://search.google.com/search-console/index) 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](https://search.google.com/search-console/sitemaps) 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](https://checklist-seo-geo.com/en/indexing-canonicalization/standardize-http-https-www-non-www), [standardize letter case and trailing slashes](https://checklist-seo-geo.com/en/architecture-navigation/standardize-letter-case-trailing-slashes) and [check canonicals and absolute URLs](https://checklist-seo-geo.com/en/indexing-canonicalization/check-canonicals-absolute-urls).

### 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`:

```python
#!/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](https://checklist-seo-geo.com/en/crawling/exclude-redirects-errors-noindex-pages) |
| 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](https://checklist-seo-geo.com/en/internal-linking/fix-links-redirects-non-canonical-urls) |
| 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](https://checklist-seo-geo.com/en/architecture-navigation/detect-orphan-pages) |
| 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](https://checklist-seo-geo.com/en/automation-quality-control/monitor-canonicals-sitemaps).

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:

```bash
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:

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

with:

```liquid
<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:

```php
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`:

```php
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`:

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

### Should internal links pointing to a redirect be fixed?

Yes, when possible. Google recommends pointing internal links to the canonical URL rather than to a duplicate, and a redirect forces an extra round trip on visitors and crawlers alike. A single link to a redirect is no big deal; hundreds of links in menus or product grids matter more. Fix the source that builds these links, such as the theme or the menu, rather than each individual link.

### Is the canonical enough if internal links point to another URL?

Not always. The canonical is a strong signal, but Google weighs it against the others: redirects, sitemap, internal links. If the whole site links to a variant, Google may select that variant despite your tag, and the indexing report shows it as a page where Google chose a different canonical than the user. Aligned signals make your preference more reliable, without ever guaranteeing it.

### How can you check the alignment of canonical, sitemap and links for free?

The free version of Screaming Frog crawls up to 500 URLs and cross-checks sitemap, canonicals and links in its Sitemaps and Canonicals tabs. Without software, a script that reads the sitemap, crawls the site from the homepage and compares, for each page, its HTTP status, its canonical and the links that cite it does the same job. In Search Console, the submitted pages filter of the indexing report reveals sitemap discrepancies.

## Resources

- [Google Search Central: How to specify a canonical URL](https://developers.google.com/search/docs/crawling-indexing/consolidate-duplicate-urls?hl=en)
- [Google Search Central: Build and submit a sitemap](https://developers.google.com/search/docs/crawling-indexing/sitemaps/build-sitemap?hl=en)
- [Screaming Frog: SEO Spider tabs guide](https://www.screamingfrog.co.uk/seo-spider/user-guide/tabs/)
- [Shopify: within filter](https://shopify.dev/docs/api/liquid/filters/within)
- [Adobe Commerce: catalog and product URLs](https://experienceleague.adobe.com/en/docs/commerce-admin/catalog/catalog/catalog-urls)
- [WP-CLI: search-replace command](https://developer.wordpress.org/cli/commands/search-replace/)
- [Next.js: sitemap file](https://nextjs.org/docs/app/api-reference/file-conventions/metadata/sitemap) and [spatie/laravel-sitemap](https://github.com/spatie/laravel-sitemap)

Next steps: [Identify and consolidate duplicates](https://checklist-seo-geo.com/en/indexing-canonicalization/identify-consolidate-duplicates) and [Compare declared and Google-selected canonicals](https://checklist-seo-geo.com/en/indexing-canonicalization/compare-declared-google-selected-canonicals).
