On this page
A URL fragment, such as #installation, identifies a location within a resource. When a URL redirects, the fragment in the browser’s final address can come from the original URL or from a redirect response. This local experiment lets you inspect both cases, including a chain of redirects and client-side navigation.
The examples below have not been run in a browser for this article. Record your own results: browser address display, scrolling, and navigation history can vary with browser behavior and page timing. The WHATWG URL Standard and RFC 9110 were not available to consult for this draft; check those documents when verifying the precise requirements for your environment.
Key Takeaways
- A redirect whose
Locationhas no fragment is intended to inherit the fragment from the URL being redirected. - A
Locationthat supplies a fragment replaces the previous fragment. An explicit empty fragment, written as a trailing#, is different from omitting the fragment. - In a redirect chain, inspect every hop: a fragment supplied by an intermediate response can be inherited or replaced later.
- HTTP redirect behavior and client-side navigation are different tests. Do not assume that assigning a new URL with JavaScript preserves the old fragment.
- Redirect headers alone do not show whether a browser ultimately scrolls to an element.
Where the fragment goes
In http://127.0.0.1:8000/start-omitted#initial, the fragment is initial. The browser does not send that fragment as part of the HTTP request target, so the server receives a request for /start-omitted. The server can nevertheless send a Location header containing a fragment.
The distinction to investigate is between URL processing and the HTTP redirect response. URL processing determines how a URL and its fragment are parsed and resolved. The HTTP redirect rule is what allows a Location without a fragment to inherit the fragment from the URL being redirected. When Location explicitly contains a fragment, including an empty one, that supplied fragment takes precedence.
The experiment below uses relative Location values. The browser resolves them against the redirecting URL and applies the redirect behavior. RFC 9110 is the relevant HTTP specification to check for fragment inheritance; the WHATWG URL Standard is relevant to browser URL parsing and serialization. Those sources have not been retrieved in this run, so the following table describes the behavior to verify rather than observed results.
Advertisement
Build the local redirect test
You need Python 3 and a browser. Save this script as fragment_test.py. It binds only to the loopback interface and uses no third-party packages.
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlsplit
REDIRECTS = {
"/start-omitted": "/final",
"/start-replaced": "/final#replacement",
"/start-empty": "/final#",
"/chain": "/middle#middle",
"/middle": "/final",
"/chain-final": "/middle-final#middle",
"/middle-final": "/final#last",
}
PAGE = b"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Fragment redirect lab</title>
<style>
section { min-height: 80vh; border-top: 1px solid #888; }
</style>
</head>
<body>
<h1>Fragment redirect lab</h1>
<p>Current address: <code id="address"></code></p>
<p>Current fragment: <code id="fragment"></code></p>
<p><a href="#replacement">Change to #replacement on this page</a></p>
<p><a href="/final">Navigate to /final without a fragment</a></p>
<p><button id="assign" type="button">Assign /final with JavaScript</button></p>
<section id="initial"><h2>initial target</h2></section>
<section id="replacement"><h2>replacement target</h2></section>
<section id="middle"><h2>middle target</h2></section>
<section id="last"><h2>last target</h2></section>
<script>
function showAddress() {
document.getElementById("address").textContent = location.href;
document.getElementById("fragment").textContent = location.hash || "(empty)";
}
showAddress();
window.addEventListener("hashchange", showAddress);
document.getElementById("assign").addEventListener("click", function () {
location.assign("/final");
});
</script>
</body>
</html>
"""
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
path = urlsplit(self.path).path
if path in REDIRECTS:
self.send_response(302)
self.send_header("Location", REDIRECTS[path])
self.send_header("Content-Length", "0")
self.end_headers()
elif path in ("/", "/final"):
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(PAGE)))
self.end_headers()
self.wfile.write(PAGE)
else:
self.send_error(404, "Not found")
if __name__ == "__main__":
server = HTTPServer(("127.0.0.1", 8000), Handler)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()
Run it from the same directory:
python3 fragment_test.py
If the port is in use, stop the other process or change 8000 in the script and the test URLs. Stop the server with Ctrl+C when finished.
Record the browser results
Open your browser’s developer tools, select the Network panel, and enable its option to preserve requests across navigation. For each URL below, enter it in the address bar and record:
- The final address shown on the page and in the address bar.
- Each redirect’s status and
Locationheader in the Network panel. - Whether the browser scrolls to a matching target. The page places targets on separate tall sections so scrolling is easier to notice.
- The request paths printed by the Python server. The fragment should not appear in those request paths.
These are expected results to check, not observations from a completed run:
| Starting URL | Redirect Location values | Fragment to check at /final |
|---|---|---|
http://127.0.0.1:8000/start-omitted#initial | /final | initial is inherited. |
http://127.0.0.1:8000/start-replaced#initial | /final#replacement | replacement replaces initial. |
http://127.0.0.1:8000/start-empty#initial | /final# | The supplied fragment is empty; initial should not be inherited. |
http://127.0.0.1:8000/chain#initial | /middle#middle, then /final | middle is supplied at the first hop and inherited at the second. |
http://127.0.0.1:8000/chain-final#initial | /middle-final#middle, then /final#last | last replaces the intermediate middle fragment. |
The page displays location.href as well as location.hash. This matters for the empty-fragment case: location.hash alone cannot reliably distinguish an absent fragment from an explicitly empty one. Compare the serialized address with the actual Location: /final# header; the browser’s address-bar display may not expose every detail.
A matching fragment and a scroll are separate observations. If the address is correct but the viewport is not where you expect, check whether the target exists, whether scripts or layout shifts moved the page, and whether scroll restoration or browser timing affected the result. Repeat without interacting with the page while it loads.
Advertisement
Test client-side navigation separately
Start at http://127.0.0.1:8000/final#initial, then try these actions one at a time, returning to that starting address before each test:
- Click Change to #replacement on this page. This is a same-document fragment navigation. Observe the address, scroll position, and whether the Network panel shows a new document request.
- Click Navigate to /final without a fragment. This link names a URL without a fragment; check that the previous
#initialis not carried into the new address merely because it was on the source page. - Click Assign /final with JavaScript. This calls
location.assign('/final'). Check the resulting address independently of the HTTP redirect cases.
A client-side router may intercept links or use the History API instead of letting the browser perform a normal navigation. For an application using such a router, repeat the experiment in the application and inspect its routing code; the lab does not model framework-specific behavior.
Inspect redirect hops separately from browser behavior
TidyURLs Redirect Checker can be used as a separate way to inspect redirect hops for a reachable test URL. It was not available to use in this run, and the local 127.0.0.1 server in this experiment may not be reachable by an online checker. For a deployed test endpoint you control, compare the reported redirects with the Location headers seen in the browser.
A hop inspection is not a substitute for the browser test. Fragments are not sent in HTTP request targets, and an HTTP-level report does not by itself establish the browser’s final address, client-side routing, or scroll behavior. Do not expose the local lab to the public internet just to run a check.
Common Mistakes
- Treating
Location: /finalandLocation: /final#as equivalent. The first omits a fragment; the second supplies an empty one. - Inspecting only the first or last response. An intermediate
Locationcan change the fragment that a later redirect inherits. - Expecting the server to receive
#initialin the request path. Look at the browser’s address and the response headers as well as the server log. - Using only
location.hashto diagnose an empty fragment. Also inspect the full serialized address and the response header. - Assuming a correct fragment guarantees a visible scroll. The target, page scripts, layout, and browser navigation behavior all matter.
Best Practices
- Test with the exact redirect chain and browser navigation path used by your application.
- Give destination sections stable, unique
idvalues and check that the target exists on the final page. - Make an explicit choice when constructing
Location: omit the fragment when inheritance is intended, or supply one when the redirect should replace it. - Keep a short record of the starting URL, each
Location, the final serialized address, and the observed scroll result for each browser you support.
Conclusion
To diagnose a URL fragment preserved after a redirect, inspect both the HTTP Location headers and the browser’s final navigation. The local lab separates omitted, replacement, empty, and chained fragments so you can see where the final fragment comes from.
What would your domain sell for?
A free TidyURLs account unlocks the Domain Estimator. It prices a name from 191,011 real domain sales.