On this page
A backslash in URL browser parsing can change where a browser sees the hostname ending and the path beginning. If a server validates the same string differently, a hostname check may approve something other than the destination the browser interprets.
This experiment compares the browser’s URL parser with Python’s urllib.parse.urlsplit. It runs locally and records components from both parsers without navigating to or fetching the example URLs.
Key Takeaways
- HTTP and HTTPS are special schemes in the WHATWG URL model. Backslashes in certain positions can be treated as separators rather than ordinary path characters.
- A server-side string split is not necessarily equivalent to browser parsing. Compare the components your application actually uses, especially the hostname and path.
- Matching parser results do not establish that a URL is safe to fetch, redirect to, or use for authorization.
- Test only local or fictional inputs unless you have permission to test a target system.
Why backslashes matter
The WHATWG URL model distinguishes special schemes, including HTTP and HTTPS, from non-special schemes. For special URLs, a backslash can act like a slash in parts of parsing where a developer might expect it to remain literal. A non-special URL can behave differently, particularly in its path.
Consider a backslash between an apparent hostname and an @ character. One parser might treat the backslash as the start of the path, while another might interpret the text before @ as user information. That difference can change the reported hostname. The experiment below records what each parser actually returns rather than assuming they agree.
The WHATWG URL Standard was not available to consult while preparing this article, and the example was not executed here. Check the standard and run the experiment with your supported browser and server versions before relying on the results.
Advertisement
Compare backslash in URL browser parsing locally
You need Python 3 and a browser with the URL API. The server parser in this example is Python’s urllib.parse.urlsplit; it is not a stand-in for every framework or HTTP client. Record your Python and browser versions with your results.
Save the following as compare_urls.py:
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlsplit
backslash = chr(92)
CASES = [
{
"label": "Backslashes after scheme and hostname",
"input": f"https:{backslash}{backslash}example.test{backslash}admin",
},
{
"label": "Single backslash after scheme",
"input": f"https:{backslash}example.test{backslash}admin",
},
{
"label": "Backslash before user-info delimiter",
"input": f"https://example.test{backslash}@other.test/path",
},
{
"label": "Backslash in HTTPS path",
"input": f"https://example.test/a{backslash}b?x=1#frag",
},
{
"label": "Backslash in non-special-scheme path",
"input": f"custom://example.test/a{backslash}b?x=1#frag",
},
]
PAGE = b'''<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>URL parser comparison</title></head>
<body>
<h1>URL parser comparison</h1>
<p>Inputs are parsed locally; the example destinations are not requested.</p>
<pre id="results">Loading...</pre>
<script>
async function run() {
const response = await fetch('/cases');
if (!response.ok) throw new Error('Could not load cases');
const cases = await response.json();
const results = cases.map((item) => {
let browser;
try {
const url = new URL(item.input);
browser = {
scheme: url.protocol.slice(0, -1),
hostname: url.hostname,
port: url.port || null,
username: url.username,
password: url.password,
path: url.pathname,
query: url.search.startsWith('?') ? url.search.slice(1) : '',
fragment: url.hash.startsWith('#') ? url.hash.slice(1) : ''
};
} catch (error) {
browser = { error: String(error) };
}
return { label: item.label, input: item.input,
server: item.server, browser };
});
document.getElementById('results').textContent =
JSON.stringify(results, null, 2);
}
run().catch((error) => {
document.getElementById('results').textContent = String(error);
});
</script>
</body>
</html>'''
def parse_on_server(value):
try:
url = urlsplit(value)
port = url.port
return {
"scheme": url.scheme,
"hostname": url.hostname or "",
"port": str(port) if port is not None else None,
"username": url.username or "",
"password": url.password or "",
"path": url.path,
"query": url.query,
"fragment": url.fragment,
}
except ValueError as error:
return {"error": str(error)}
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/":
body = PAGE
content_type = "text/html; charset=utf-8"
elif self.path == "/cases":
results = [
{**case, "server": parse_on_server(case["input"])}
for case in CASES
]
body = json.dumps(results).encode("utf-8")
content_type = "application/json; charset=utf-8"
else:
self.send_error(404)
return
self.send_response(200)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
if __name__ == "__main__":
with HTTPServer(("127.0.0.1", 8765), Handler) as server:
try:
server.serve_forever()
except KeyboardInterrupt:
pass
Start it in a terminal:
python3 compare_urls.py
Open http://127.0.0.1:8765/ in the browser. The page requests only the local /cases endpoint; constructing a URL object does not itself fetch the fictional example destinations. Stop the server with Ctrl+C. If the port is already in use, change 8765 in the script and in the address you open.
For each case, save the displayed JSON with the runtime versions. Compare hostname, username, and path first, then inspect the remaining fields and any errors. The browser and Python representations are normalized only enough to make this comparison readable; they are not guaranteed to serialize every URL identically. In particular, an empty query delimiter and an absent query are not distinguished by this display.
Extend the experiment to your stack
Replace or supplement parse_on_server with the parser your validator or routing middleware actually uses. Also capture the representation used by the component that consumes the URL—for example, a redirect handler or an HTTP client. A framework may apply additional parsing or normalization after your initial check.
Add controlled cases for explicit ports, encoded characters, empty components, and malformed inputs relevant to your application. Record errors as well as successful parses. Do not infer the final destination from a string prefix or from one component alone.
Advertisement
Parser agreement is not a security policy
Even when the parsers agree on a hostname, that hostname may resolve to a prohibited address, or the destination may redirect somewhere else. Choose controls for what your application does with the URL:
- For redirects: restrict schemes and destinations to your policy, and evaluate the parsed destination rather than searching the raw string for an approved domain.
- For link previews and other server-side fetches: restrict schemes, hostnames, and resolved IP addresses; account for loopback, private, link-local, and other prohibited ranges, including IPv6. Revalidate every redirect and enforce network egress restrictions.
- For DNS: guard against changes between validation and connection, including DNS rebinding. Ensure the address actually connected to is permitted; a preflight hostname lookup alone is insufficient. Consider proxy behavior too.
- For resource use: set connection and read timeouts, redirect limits, and response-size limits. Require authentication and authorization where the feature needs them.
A URL parser is useful for identifying components, not for enforcing all of these boundaries.
Common Mistakes
- Checking the raw prefix: A string that appears to start with an approved hostname may parse into different user-info, host, or path components.
- Testing only ordinary URLs: Include backslashes near the scheme, authority, and path, plus malformed inputs and non-special schemes if your application accepts them.
- Assuming all server parsers behave like browsers: Test the exact parser and downstream consumer used in production.
- Treating successful parsing as validation: Parsing tells you how a string was interpreted, not whether the resulting action is authorized or safe.
- Testing against third-party systems: Use fictional hostnames and isolated infrastructure for experiments.
Best Practices
Define an explicit allowlist of schemes and destinations for each feature. Parse before applying the policy, reject ambiguous forms when your application does not need them, and pass the validated representation to the consumer where possible. Add regression tests for every disagreement you discover, using the same runtimes and configuration you deploy.
Conclusion
Backslashes are a useful way to expose assumptions about URL boundaries. Measure the browser and server interpretations locally, then apply a separate security policy to the action your application performs.
What would your domain sell for?
A free TidyURLs account unlocks the Domain Estimator. It prices a name from 191,011 real domain sales.