Sub topic 10
Canonical URLs and duplicate content
This chapter assumes you know how a crawler fetches pages and follows redirects, and that you can read short Python snippets. It covers how a search engine decides which URL represents a page and what it does when many URLs lead to the same content.
Why duplicates exist
A search engine wants one index entry per piece of content. The web does not cooperate. One article can be reachable at all of these addresses:
http://example.com/guideandhttps://example.com/guidehttps://www.example.com/guideandhttps://example.com/guidehttps://example.com/guide?utm_source=newsletterhttps://example.com/guide?print=1https://example.com/guide/with a trailing slash
To the crawler these are different URLs, because a URL is only a string until something proves otherwise. If the engine indexed all of them, results would fill with copies, and ranking signals such as links would split across the copies. The engine also wastes crawl budget fetching pages it already has.
The engine therefore groups duplicates into a cluster and picks one canonical URL. This is the representative address that appears in results and receives the combined signals. The other members are still known, but they are usually not shown.
Two kinds of duplication
Duplicates fall into two levels, and the tools for each differ.
| Level | What matches | Example | Typical detection |
|---|---|---|---|
| URL-level | Different strings, same resource | Tracking parameters, parameter order, default ports | Normalization rules |
| Content-level | Different resources, same or near-same text | Print view, mirror site, product page in two categories | Hashing and similarity fingerprints |
Normalization is cheap and runs during URL discovery, before any fetch. Content comparison runs after the fetch and rendering steps, so it costs a request first.
Normalizing URLs before fetching
Normalization rewrites a URL into a standard form so that trivially different strings collapse into one. Safe rules include lowercasing the scheme and host, removing the default port, removing the fragment, and sorting query parameters. Removing known tracking parameters is a common site-specific rule.
from urllib.parse import urlsplit, urlunsplit, parse_qsl, urlencode
TRACKING = {"utm_source", "utm_medium", "utm_campaign", "utm_term",
"utm_content", "gclid", "fbclid"}
DEFAULT_PORTS = {"http": 80, "https": 443}
def normalize(url):
parts = urlsplit(url)
scheme = parts.scheme.lower()
host = (parts.hostname or "").lower()
netloc = host
if parts.port and parts.port != DEFAULT_PORTS.get(scheme):
netloc = f"{host}:{parts.port}"
path = parts.path or "/"
query = sorted(
(k, v)
for k, v in parse_qsl(parts.query, keep_blank_values=True)
if k.lower() not in TRACKING
)
return urlunsplit((scheme, netloc, path, urlencode(query), ""))
urls = [
"HTTP://Example.com:80/guide?b=2&a=1&utm_source=news#top",
"http://example.com/guide?a=1&b=2",
"https://example.com/guide?a=1&b=2",
"http://example.com",
]
for u in urls:
print(normalize(u))The output is:
http://example.com/guide?a=1&b=2
http://example.com/guide?a=1&b=2
https://example.com/guide?a=1&b=2
http://example.com/The first two collapse into one URL. The third stays separate because http and https are different schemes, and the code cannot know they serve the same page.
The function leaves the path case alone and keeps trailing slashes. On many servers /Guide and /guide are different resources, and /guide and /guide/ may differ too. A normalizer that guesses wrong merges pages that are not duplicates, and that error is worse than missing a duplicate.
Detecting identical content
After fetching, an engine can compute a fingerprint of the extracted main text. If two URLs produce the same fingerprint, they are exact duplicates.
import hashlib
import re
pages = {
"https://example.com/guide": "Crawlers follow links. Indexes map words.",
"https://example.com/guide?print=1": "Crawlers follow links. Indexes map words.",
"https://example.com/other": "Something else entirely.",
}
def fingerprint(text):
cleaned = re.sub(r"\s+", " ", text.lower()).strip()
return hashlib.sha256(cleaned.encode("utf-8")).hexdigest()
groups = {}
for url, text in pages.items():
groups.setdefault(fingerprint(text), []).append(url)
for members in groups.values():
if len(members) > 1:
print(members)It prints ['https://example.com/guide', 'https://example.com/guide?print=1']. Collapsing whitespace and case before hashing is what lets the two copies match, even though the raw strings differ.
A cryptographic hash changes completely if one character changes, so it only finds exact copies. Real systems also detect near-duplicates, such as two pages that share a long article but have different sidebars. Common techniques split text into overlapping word sequences called shingles and compare the sets, or use a locality-sensitive hash such as SimHash, which gives similar texts similar fingerprints. Engines usually fingerprint the main content and ignore navigation and footers. Otherwise every page on a site would look partly alike.
Signals that pick the canonical
Once a cluster exists, the engine must choose its representative. Site owners can supply several signals, and they differ in strength.
- Redirects. A permanent redirect (301 or 308) from a duplicate to the preferred URL is a strong signal. The crawler follows it, and the destination becomes the likely canonical.
rel="canonical". A link element in the page head names the preferred URL.- Sitemap inclusion. Listing a URL in a sitemap suggests you consider it canonical. The signal is weak.
- Internal links. If your site links to one version consistently, that version looks preferred.
- HTTPS. Given a choice, engines tend to prefer the secure version.
The rel="canonical" element looks like this:
<link rel="canonical" href="https://example.com/guide">Place it in the <head> and use an absolute URL. A relative href can be resolved against the wrong base, and an element outside the head is often ignored.
A canonical is a hint
rel="canonical" is a suggestion, not a command. The engine compares your declaration with the other signals and may choose a different URL. Typical reasons:
- The two pages are not actually similar, so the engine treats the tag as a mistake.
- Your internal links, redirects, and sitemap all point to a different URL than the tag does.
- The declared canonical returns an error, redirects elsewhere, or cannot be fetched.
If you need a duplicate gone for certain, a redirect is the stronger tool. Use rel="canonical" when the duplicate must remain reachable, for example a print view or a filtered list.
Edge cases and common mistakes
- Canonical chains. Page A names B, and B names C. Engines may follow the chain, but it is unreliable. Point every duplicate directly at the final URL.
- Conflicting signals. A page whose tag names URL X while the sitemap lists URL Y gives the engine nothing consistent to follow, so the choice becomes unpredictable.
- Multiple canonical tags. Two tags with different values are commonly ignored. Plugins and templates can both inject one, so check the rendered output.
- Canonical in JavaScript. If script inserts the tag, it only counts after rendering. Static HTML is safer.
- Canonical plus noindex. A
noindexpage that points its canonical at another page sends mixed messages. Choose one intent per page. - Canonical to a blocked URL. If robots.txt blocks the canonical target, the crawler can never confirm it. Keep canonical targets crawlable.
- Every page canonical to the homepage. This is a frequent misconfiguration. The pages are not duplicates of the homepage, so the engine ignores the tag, or worse, drops pages from the index.
- Paginated lists. Page 2 of a list is not a duplicate of page 1. Pointing all pages at page 1 hides the items listed on later pages.
- Language variants. A French page and an English page are different content. Declare their relationship with
hreflangannotations, not a canonical tag.
Checking the result
The URL you declared is not always the URL the engine chose. Search engine consoles usually report both a user-declared canonical and a selected canonical for a page. When they differ, compare the signals listed above and look for the inconsistency. To audit your own pages, fetch several variants with a script and confirm that each one redirects to, or declares, the same final URL.
Exercise
A site publishes /shoes?color=red and /shoes?color=blue. The pages list different products, but both contain a rel="canonical" tag pointing to /shoes. The owner finds the colored pages are missing from the index. Why might this happen, and what is a better setup?
Show answer
The two pages are not duplicates of /shoes, because their product lists differ. The engine treats the tag as a hint and may honor it, which merges the colored pages into /shoes and leaves their products out of the index. If each color page should be findable, give it a self-referencing canonical (or none) and link to it normally. If the color filters add nothing worth indexing, canonicalizing to /shoes is acceptable only when the main page lists the same products.
Exercise
Why does the normalize function in this chapter keep the path case and trailing slash unchanged, even though changing them would merge more URLs?
Show answer
Servers may treat /Guide and /guide, or /guide and /guide/, as different resources. Merging them by rule can combine pages that are not duplicates and hide one from the index. Content fingerprinting and redirect or canonical signals are safer ways to decide that such URLs match.