Sub topic 3
Normalizing URLs to expose hidden duplicates
This chapter assumes you can read a crawl export (one row per URL, with status code and content fields), you know how HTTP redirects work, and you can group rows in pandas or a spreadsheet. The earlier chapters defined exact duplicates, near duplicates and thin pages. Here you handle the cheapest source of duplication: one page reachable under many URL spellings.
Why URL variants create duplicates
A crawler treats each distinct URL string as a separate page. A server often does not. These URLs can all return the same product page:
http://Example.com/shoes/?utm_source=news&color=redhttps://example.com/shoes?color=redhttps://example.com/shoes/?color=red&fbclid=abc#reviews
A crawl export lists them as three rows with three sets of metrics. If you count duplicates by comparing raw URLs, you miss the problem. If you hash the body text, you find it, but only for variants the crawler actually fetched and rendered the same way. Normalizing the URL first gives you a key: a string that is the same for every variant you believe is one page. Grouping by that key shows how many spellings each page has.
Normalization has two uses:
- Diagnosis. It shows which variants exist in your crawl and how many internal links, sitemap entries or external links point at each one.
- Validation. It lets you check whether your canonical tags and redirects already collapse the variants.
It does not decide what the search engine treats as one page. It is your hypothesis, and you test it against the site's real behavior.
The common variant types
| Variant | Example | Normalization rule |
|---|---|---|
| Protocol | `http://` vs `https://` | Force one protocol |
| Host case | `Example.com` vs `example.com` | Lowercase the host |
| Trailing slash | `/shoes/` vs `/shoes` | Pick one form |
| Tracking parameters | `?utm_source=news` | Drop known tracking names |
| Parameter order | `?a=1&b=2` vs `?b=2&a=1` | Sort parameters |
| Fragment | `#reviews` | Remove it |
| Host prefix | `www.example.com` vs `example.com` | Choose one, based on the site |
| Index files | `/shoes/index.html` vs `/shoes/` | Strip only if the server treats them as the same |
The last two rows are not in the function below, because they depend on how a particular site is configured.
A normalization function
This function applies the rules from the table that do not depend on the site.
from urllib.parse import urlsplit, urlunsplit, parse_qsl, urlencode
TRACKING = {"utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "gclid", "fbclid"}
def normalize(url):
parts = urlsplit(url)
host = parts.netloc.lower()
path = parts.path or "/"
if path != "/" and path.endswith("/"):
path = path.rstrip("/")
query = sorted((k, v) for k, v in parse_qsl(parts.query) if k not in TRACKING)
return urlunsplit(("https", host, path, urlencode(query), ""))
print(normalize("http://Example.com/shoes/?utm_source=news&color=red"))
# https://example.com/shoes?color=redEach line does one job:
urlsplitbreaks the URL into scheme, host, path, query and fragment, so you edit each part separately instead of using string replacement.parts.path or "/"turns an empty path (https://example.com) into/, so the home page has one form.- The slash rule keeps the root
/and strips a trailing slash from every other path. - The list comprehension removes tracking names and
sortedputs the remaining pairs in a fixed order. urlunsplitrebuilds the URL withhttpsand an empty fragment.
Applying it to a crawl export
Normalize every row, then group by the key. Any group with more than one raw URL is a set of variants.
import pandas as pd
from urllib.parse import urlsplit, urlunsplit, parse_qsl, urlencode
TRACKING = {"utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "gclid", "fbclid"}
def normalize(url):
parts = urlsplit(url)
host = parts.netloc.lower()
path = parts.path or "/"
if path != "/" and path.endswith("/"):
path = path.rstrip("/")
query = sorted((k, v) for k, v in parse_qsl(parts.query) if k not in TRACKING)
return urlunsplit(("https", host, path, urlencode(query), ""))
urls = [
"http://Example.com/shoes/?utm_source=news&color=red",
"https://example.com/shoes?color=red",
"https://example.com/shoes/?color=red&fbclid=abc#reviews",
"https://example.com/boots/",
]
df = pd.DataFrame({"url": urls})
df["normalized"] = df["url"].map(normalize)
groups = df.groupby("normalized")["url"].agg(list)
variants = groups[groups.str.len() > 1]
print(variants)The three /shoes rows land in one group under https://example.com/shoes?color=red. The boots page has a single spelling and is not listed.
With a real export, keep more columns than url. Aggregate the status code, inlinks count and canonical target for each group. A group where one variant returns 200 and the others return 301 is healthy. A group where all variants return 200 with no canonical is the problem you are looking for.
What the groups tell you
Look at three things for each group.
- Which variants return 200. A variant that redirects (301) to the preferred URL is already handled. A variant that returns 200 can be indexed, so it is a duplicate candidate.
- Where the links point. If internal links use the non-preferred form, the site itself is promoting the duplicates. Fixing the links is often cheaper than adding canonical tags.
- What the server does with the variant. Request a few variants directly and compare. If
/shoesand/shoes/both return the same body with status 200, they are real duplicates. If one returns 404, the crawler found a stray link and nothing needs consolidating.
Redirect chains matter too. If http://example.com/shoes/ redirects to https://example.com/shoes/, which then redirects to https://example.com/shoes, the crawl shows two hops. That is a performance and signal-loss issue, separate from duplication, but normalization makes it visible because the first and last URLs share a key.
Gotchas
Normalization is a heuristic, and each rule can be wrong for a given site.
- Trailing slash. Some sites use the slash form for directory-like pages and the plain form for files. Removing it everywhere can merge distinct URLs. Check the site's convention first.
- Forced https. The function assumes the site runs on https. If part of the site really serves only http, the key will not match a URL you can fetch. Use the key for grouping and keep the original URL when you need to request a page.
- Blank parameter values.
parse_qsldrops pairs such as?filter=by default. Passkeep_blank_values=Trueif blank values appear on the site. - Parameters that change content.
page=2,sort=price,id=17andlang=deproduce different content. The function keeps them on purpose. Only add a name toTRACKINGwhen you know it has no effect on the response. The next chapter covers parameter, faceted and paginated URLs. - Host prefix.
www.example.comandexample.comare different hosts. The function lowercases the host but does not removewww. Decide which host is preferred and add that rule tonormalize, or the two groups stay separate. - Ports and credentials.
parts.netlocincludes any port or user information. A URL such ashttps://example.com:443/keeps:443in the key. Useparts.hostnameif your crawl contains these. - Encoding.
%7Eand~, or%2fand%2F, can appear in the same crawl.urlencodere-encodes the query, but the path is left as given. Compare a handful of paths by eye before trusting a group count.
How this fits the larger workflow
Normalization is the first pass because it needs only URLs. It narrows your work before you spend effort on content comparison:
- URLs that share a key but return different body text are not true duplicates. Something else, such as a parameter you decided to ignore, is changing the content, and your rule needs refining.
- URLs that share a key and share a content hash are exact duplicates caused by URL variation. These are the best candidates for redirects or canonical tags.
- URLs with different keys but the same content hash are duplicates your rules did not predict. They go to the exact-duplicate and near-duplicate steps in later chapters.
Exercise
Your crawl has https://shop.example/Boots and https://shop.example/boots, both returning 200. The normalize function leaves them in separate groups. Should you change the function to lowercase the path so they merge? What do you check first?
Show answer
Do not change it until you confirm how the server behaves. Request both URLs and compare the status codes, the body text (or a content hash) and any canonical tags. If both return the same content, they are real duplicates, and you can add path lowercasing to your key for this site and recommend a redirect to one form. If they return different content, or one returns 404, lowercasing would merge distinct pages or hide a broken link, so the rule is wrong for this site.
Exercise
A group has four raw URLs. Three return 301 to the fourth, which returns 200. What does this tell you about the group, and what should you still check?
Show answer
The server already collapses the variants into one preferred URL, so the group is handled and is not an indexing problem. Still check that the preferred URL is the one in your internal links and sitemap. If internal links point at the redirecting variants, the site sends crawlers through unnecessary redirects. Also check that the redirects are a single hop and not a chain.