URL Normalization for Deduplication Without Merging Different Pages

Learn which URL differences are safe to normalize, which can hide distinct pages, and how to build auditable comparison keys for deduplication.

Published
Reading time
8 min read
URL Normalization for Deduplication Without Merging Different Pages
On this page

Cleaning a URL dataset often means deciding whether two different-looking URLs represent the same page. Some transformations are usually safe, such as lowercasing a hostname; others, such as reordering query parameters, can merge distinct resources. This guide explains a conservative approach to URL normalization for deduplication, with examples and Python code that keeps risky transformations out of the comparison key.

Key Takeaways

  • Normalize only what your application considers equivalent. There is no universal deduplication key for every website or URL use case.
  • Lowercasing the scheme and hostname and removing a scheme’s default port are generally safe URL-level normalizations.
  • Keep paths and queries unchanged unless you know the server treats the proposed variants as equivalent.
  • Fragments are not sent in an HTTP request, but can matter to browser-side applications. Decide whether they belong in your deduplication key.
  • Store the original URL alongside the normalized key so every merge is auditable and reversible.

Decide What “Duplicate” Means First

A URL can identify a server resource, a browser-visible location, or an application-specific page. Those are not always the same thing. For example, a website may use a fragment to select a section in a single-page app, or use query parameters to choose a product variant.

Before normalizing, define the comparison goal:

  • HTTP request deduplication: Compare URLs by the request target sent to the server. A fragment is not part of that target, so it may be excluded.
  • Browser-location deduplication: Preserve fragments because they can affect the location displayed or interpreted by client-side code.
  • Application-level deduplication: Apply rules based on the site’s known routing and parameter behavior, and document those rules separately.

Standards describe URL syntax and normalization techniques, but they do not provide one comparison key that is correct for every application. A conservative key is a starting point—not proof that two pages are interchangeable.

Usually low-risk URL-level changes

For ordinary HTTP and HTTPS URLs, these changes are generally appropriate for a conservative comparison key:

  • Lowercase the scheme and hostname. Scheme and DNS hostnames are case-insensitive.
  • Remove the default port for the scheme: :80 for HTTP and :443 for HTTPS.

Even these choices should be explicit in your dataset policy. Keep non-default ports, and do not treat http and https as interchangeable.

Changes that depend on the application

Consider these only when your use case supports them:

  • Dropping fragments: often suitable for comparing server requests, but not necessarily browser-side pages.
  • Removing a trailing slash or treating an empty path as /: servers and routing frameworks can distinguish these.
  • Removing tracking parameters: a parameter that looks like analytics metadata might still affect content or access.
  • Converting internationalized hostnames or normalizing path characters: rules and server behavior need careful handling.

Advertisement

Paired Examples: When to Merge and When Not To

URL pairConservative decisionWhy
HTTP://Example.com:80/a and http://example.com/aSame keyScheme and hostname casing differ, and port 80 is the HTTP default.
https://example.com:443/a and https://example.com/aSame keyPort 443 is the HTTPS default.
https://example.com/a#intro and https://example.com/a#faqDepends on the goalThe fragment is not sent in an HTTP request, but client-side code may use it to select different content.
https://example.com/item?color=red&size=m and https://example.com/item?size=m&color=redKeep separate by defaultA server or application can treat query order as meaningful, especially with repeated parameters or signed URLs.
https://example.com/a%2Fb and https://example.com/a/bKeep separate%2F is an encoded reserved character; decoding it changes the path separator structure.
https://example.com/page?campaign=spring and https://example.com/pageKeep separate unless verifiedThe parameter may affect page content, attribution, or application behavior.

The percent-encoding distinction matters beyond slashes. RFC 3986 permits normalization of percent-encoded unreserved characters in some comparison contexts, but reserved characters can act as delimiters. Decoding a reserved character can change how a path or query is parsed. A conservative dataset key can simply preserve percent-encoding as written rather than trying to guess which server-side interpretation applies.

Query strings deserve similar caution. Even if a particular application treats different parameter orders as equivalent, repeated keys can be order-sensitive, and some systems use the exact query string when generating or verifying signatures. Do not sort parameters or remove values as a general-purpose cleanup step.

Build a Conservative Comparison Key in Python

This example changes only the scheme casing, hostname casing, and default HTTP(S) port. It preserves the path, query string, and fragment by default. Set drop_fragment=True only when your comparison is specifically about server requests and that matches your use case.

from urllib.parse import urlsplit, urlunsplit


def comparison_key(url: str, *, drop_fragment: bool = False) -> str:
    """Build a conservative key for an absolute HTTP(S) URL.

    This is a dataset comparison helper, not a URL validator or security filter.
    It rejects userinfo rather than attempting to rewrite credentials in a URL.
    """
    parts = urlsplit(url)
    scheme = parts.scheme.lower()

    if scheme not in {"http", "https"}:
        raise ValueError("Only absolute HTTP and HTTPS URLs are supported")
    if not parts.netloc or parts.hostname is None:
        raise ValueError("URL must include a hostname")
    if parts.username is not None or parts.password is not None:
        raise ValueError("URLs containing userinfo are not supported")

    try:
        port = parts.port
    except ValueError as exc:
        raise ValueError("URL contains an invalid port") from exc

    host = parts.hostname.lower()
    # IPv6 literals need brackets when reconstructed in the authority.
    authority = f"[{host}]" if ":" in host else host

    default_port = 80 if scheme == "http" else 443
    if port is not None and port != default_port:
        authority = f"{authority}:{port}"

    fragment = "" if drop_fragment else parts.fragment
    return urlunsplit((scheme, authority, parts.path, parts.query, fragment))


first = "HTTP://Example.com:80/a?x=1#top"
second = "http://example.com/a?x=1#top"
assert comparison_key(first) == comparison_key(second)

query_a = "https://example.com/item?color=red&size=m"
query_b = "https://example.com/item?size=m&color=red"
assert comparison_key(query_a) != comparison_key(query_b)

fragment_a = "https://example.com/a#intro"
fragment_b = "https://example.com/a#faq"
assert comparison_key(fragment_a) != comparison_key(fragment_b)
assert comparison_key(fragment_a, drop_fragment=True) == comparison_key(
    fragment_b, drop_fragment=True
)

The function is deliberately limited: it does not validate that a URL is safe to fetch, determine whether a page exists, or establish that two URLs return equivalent content. It also does not normalize paths, query parameters, percent-encoding, or internationalized hostnames. Those transformations need a policy based on the application and, where relevant, the server’s behavior.

For a dataset pipeline, keep the source and derived value in separate fields:

original_url                         comparison_key
HTTP://Example.com:80/a?x=1#top      http://example.com/a?x=1#top

This makes the transformation reviewable and lets you regenerate keys if your policy changes. If records are merged, retain the source record identifiers or a list of contributing original URLs as well.

A Practical Deduplication Workflow

  1. Keep the input untouched. Store the original string and any source-row or record identifier.
  2. Parse and classify. Separate valid absolute HTTP(S) URLs from malformed input, relative references, and unsupported schemes. Do not silently repair ambiguous input.
  3. Apply a documented key policy. Start with scheme and hostname casing plus default-port removal. Decide explicitly whether fragments are retained.
  4. Preserve potentially meaningful components. Leave paths, queries, and percent-encoding unchanged unless an application-specific rule has been verified.
  5. Group by the key, not by a rewritten source value. Keep the original URLs in each group so reviewers can see what was combined.
  6. Review high-impact rules. Test proposed transformations against representative URLs, including repeated query parameters, encoded delimiters, and routes with and without trailing slashes.
  7. Measure collisions before merging records. A collision is evidence that the key maps multiple inputs together; it is not by itself evidence that those inputs represent the same page.

Advertisement

Common Mistakes

  • Sorting query parameters by default. This assumes order is irrelevant and can break repeated parameters, signed URLs, or application-specific behavior.
  • Removing every parameter that looks like tracking. Parameter names do not prove that a value is irrelevant to the resource.
  • Decoding all percent-encoded characters. Reserved characters can change the structure of a URL when decoded.
  • Dropping every fragment without choosing a comparison goal. That is often reasonable for server-request deduplication, but can merge different client-side states.
  • Treating a normalized key as a canonical URL. A comparison key is a data-processing choice. It does not establish the site’s canonical URL or guarantee equivalent responses.
  • Overwriting the original input. Without the source value, auditing and reversing a merge becomes harder.
  • Using URL normalization as fetch security. A parser or normalized key is not an SSRF defense and does not make a URL safe to request.

Best Practices

  • Write down the meaning of “duplicate” for the dataset before implementing normalization.
  • Use the smallest transformation set that meets that definition.
  • Keep original URLs, normalized keys, and normalization-policy versions in separate fields.
  • Add test cases for every rule, including cases that must remain distinct.
  • Reassess the policy when the data source, target application, or deduplication goal changes.
  • For application-specific equivalence, verify behavior with the application or its owners rather than inferring it from URL appearance alone.

Conclusion

Reliable URL deduplication depends on conservative rules and a clear definition of equivalence. Normalize obvious URL-level differences, preserve paths and queries by default, and retain the original URLs so every match can be inspected. Treat more aggressive transformations as application-specific decisions, not universal cleanup.

References

What would your domain sell for?

A free TidyURLs account unlocks the Domain Estimator. It prices a name from 191,011 real domain sales.