A collector reduces its queue by removing every query string. Request counts fall, but page two, French content, and several product sizes disappear with them.
I would approve a URL transformation only after identifying what it can merge. The first goal is a reproducible queue identity for a defined collection task. That is different from rewriting the request URL or claiming that two pages contain the same business record.
This guide is for authorized HTTP GET collection with explicit target scope. It uses conservative queue keys and source-specific evidence. It does not provide a universal canonicalizer for browser applications, signed APIs, or every website.
Separate three kinds of identity
A discovered link, a network retrieval task, and an extracted record can have different identities. Two links with different fragments may lead to the same ordinary HTTP retrieval. A single URL can produce different language or regional representations. Two different URLs can contain the same product record.
Keep the originally discovered URL for provenance. Define a queue key that includes the relevant request context. Apply record-level identity after extraction using the fields the task actually needs. Do not replace all three with one cleaned URL.
This distinction complements valid-record accounting. Fewer queued URLs is not evidence of less duplicate data if meaningful variants were discarded before retrieval.
Review transformations by what they can erase
RFC 3986 defines URI components and normalization. Scheme and hostname case can be normalized; other components have different rules. Reserved characters must not be decoded indiscriminately because doing so can change their role as delimiters.
| Proposed transformation | Risk | Decision for the conservative example |
|---|---|---|
| Lowercase the scheme and hostname | Low for the intended HTTP identity | Do it in the key |
| Normalize an implicit HTTP(S) default port | Low for the intended origin identity | Use the effective numeric port |
| Lowercase the whole URL | Can merge distinct paths or query values | Preserve path and query case |
| Remove the entire query | Can erase pagination, filters, language, signatures, or versions | Preserve it |
| Sort query parameters | Can change application-specific or signed-request meaning | Preserve order |
| Remove repeated or blank query values | Can erase selection semantics | Preserve exact query text |
| Decode every percent escape | Can turn encoded delimiters into structural delimiters | Preserve escapes |
| Remove trailing slashes or replace HTTP with HTTPS | Can change the resource or origin | Do not assume equivalence |
| Drop a fragment for ordinary HTTP retrieval | Can be appropriate for the network request | Do it only in this retrieval key; retain the original link |
A parameter named utm_source may be a candidate for a source-specific exclusion rule. Its familiar name alone is not proof that removing it has no effect on your task. Signatures, redirects, experiments, and attribution-sensitive validation can make apparently cosmetic differences important.
Include the representation context
If the task distinguishes English/US and French/France output, those contexts need separate queue identities even when the URL is identical. The context identifier can represent a versioned combination of language, market, authenticated account scope, and other relevant request settings.
Do not insert raw cookies or bearer tokens into a key or log. Use a nonsecret identifier for the approved request configuration. The HTTP cookie explanation describes why request state is separate from the visible URL.
Not every proxy change needs a new logical task. If a retry uses another network route while preserving the required representation, it is still an attempt at the same task. If region is part of the output contract, verify that region and preserve it in the task context. See testing location and session behavior separately for the distinction.
A conservative key without rewriting requests
The following function creates a Python tuple for an HTTP retrieval queue. It does not remove tracking fields, sort a query, resolve dot segments, normalize every valid URI spelling, or generate an outgoing URL. It intentionally tolerates duplicate work rather than merge inputs whose equivalence has not been established.
import re
from urllib.parse import urlsplit
def collection_key(url, context_id, approved_origins):
"""Queue identity for HTTP GET collection, not a URL rewrite or fetch guard."""
if not isinstance(url, str) or not isinstance(context_id, str) or not context_id:
raise ValueError("Expected a URL string and a nonempty, nonsecret context ID")
# Refuse inputs the parser might otherwise clean up silently.
if any(ord(c) <= 32 or ord(c) >= 127 for c in url) or "\\" in url:
raise ValueError("Use an ASCII URL without whitespace, controls, or backslashes")
if re.search(r"%(?![0-9A-Fa-f]{2})", url):
raise ValueError("Invalid percent escape")
parts = urlsplit(url)
if parts.scheme not in {"http", "https"} or not parts.hostname:
raise ValueError("Expected an absolute HTTP(S) URL")
if parts.username is not None or parts.password is not None:
raise ValueError("Credentials must not appear in queue URLs")
port = parts.port
if port is None:
port = 443 if parts.scheme == "https" else 80
origin = (parts.scheme, parts.hostname, port)
if origin not in approved_origins:
raise ValueError("Origin is outside this queue's approved scope")
# Fragment is excluded only for this HTTP retrieval queue.
query_present = "?" in url.split("#", 1)[0]
return (context_id, *origin, parts.path or "/", parts.query, query_present)
Use it with explicit scope:
approved = {("https", "example.com", 443)}
key = collection_key(
"https://example.com/product?id=12&size=M#details",
"public-en-us-v1",
approved,
)
The result includes public-en-us-v1, the normalized origin, /product, id=12&size=M, and an indicator that a query delimiter was present. The original URL remains in the task record. Use an unambiguous serialization such as JSON if the key must leave the process; do not concatenate fields with a delimiter that might also appear inside them.
The query-presence flag keeps /page distinct from /page?. This is deliberately conservative. The function also preserves percent-escape spelling and query order, so it may keep two equivalent requests separate. Reducing those false negatives requires additional justified normalization; it should not happen accidentally through parsing and reconstruction.
Python's urllib.parse documentation warns that its parsing functions do not validate URLs. The sample therefore rejects certain inputs before parsing and checks the parsed origin. These checks define the queue's input scope, not a complete network-security boundary. An actual fetcher still needs redirect validation, DNS/private-address controls where appropriate, and source-specific authorization.
For browser tasks that use fragments as application state, do not use this HTTP-only key as the browser-task key. A fragment can drive client-side routing even though it is not sent as part of the ordinary HTTP request target.
Prove collisions are acceptable before changing the policy
Before adopting a new normalization rule, run it against an authorized representative URL sample. Preserve the old and proposed keys, then inspect every group that the new rule would merge. Compare the fields that matter: record IDs, pagination position, market, language, currency, selected variant, and any version identifier.
A collision is not automatically an error. It becomes a problem when merged tasks require different outputs. Conversely, equal body text does not prove the policy is safe for every future state of the source.
For a signed URL, keep the request unchanged. If multiple temporary signed URLs are known to identify the same immutable object, use a trusted object/version identifier for a separate business task key. Do not strip signature parameters and send the altered URL.
Define what happens to already queued tasks when the key policy changes. Version the policy, retain enough provenance to replay wrongly merged tasks, and avoid applying a new key to only half the workers. If the store uses a digest of a serialized key, retain the structured fields under appropriate controls for diagnosis; a hash does not prove the underlying equivalence assumption.
What was checked
The function was exercised with Python 3.11.15 using 17 offline checks. Those covered hostname/scheme case, default ports, empty paths, HTTP-fragment handling, query order, repeated values, blank values, an empty query delimiter, path case, reserved percent escapes, different contexts, and rejection of credentials, a foreign origin, controls, malformed escapes, invalid ports, and relative links.
These checks demonstrate the stated key behavior. They do not prove that a particular site's query fields are interchangeable, that all URL forms are supported, or that a live website has no duplicate pages. The code performs no network requests and is not a complete crawler.
Start with the conservative key. Add one source-specific equivalence rule at a time, inspect its collisions, and retain the ability to replay candidates. Saving requests is useful only if the output contract survives the reduction.
Frequently asked questions
Can a canonical link replace my collection key?
Treat it as a publisher-provided signal, not automatic proof of equivalence for every task. Verify whether the source still exposes differences you need, such as market, language, pagination, or variants, before merging collection work.
Should I convert the query into a dictionary?
Not for this conservative identity. A plain dictionary can lose repeated keys or their ordering. The example preserves the original query text instead of interpreting the application's query semantics.
Does removing fragments always preserve the task?
No. It can preserve an ordinary HTTP retrieval identity while changing a browser application task. Keep the original link and define separate browser-state identity where needed.
Can two proxy exits share one queue key?
Yes, when they are alternative routes for the same output context. If the task intentionally compares regions or other representation conditions, keep those contexts distinct and verify the actual responses rather than inferring them from an exit label alone.
About the author
陈序 is a virtual editorial author focused on proxy product selection and application analysis, translating task requirements into clear acceptance criteria and practical trade-offs.
Expertise: Proxy product selection; application fit; plan and billing conditions; trial acceptance; long-term operating requirements.