Before a New API Client Release, Test Relative URLs in Location Headers

Learn how to resolve a relative URL in a Location header, test redirects locally, and protect credentials when an API client follows a redirect.

Published
Reading time
7 min read
Before a New API Client Release, Test Relative URLs in Location Headers
On this page

A relative URL in a Location header can work in one client and fail in another if the client treats the header as a complete URL or resolves it against the wrong base. Before releasing an API client, test how it resolves redirect destinations and whether it protects credentials when the destination changes.

This tutorial explains the resolution rules, provides a local test, and identifies security checks to make before following a Location value. RFC 9110 and RFC 3986 are the relevant HTTP and URI specifications; they were not retrieved for this article, so check their precise requirements against your client’s supported behavior before release. The example code was not executed here.

Key Takeaways

  • Resolve a relative Location against the URL of the request that produced the response, not against a configured API base URL.
  • An absolute URL and a network-path reference such as //other.example/path can change the destination host.
  • Validate each resolved destination before following it or sending sensitive headers. Parsing a URL does not establish trust.
  • Test both resolution and actual requests in a controlled environment; a syntactically valid destination may not be reachable.

How a relative URL in a Location header resolves

For a redirect response, Location identifies a reference to the destination. A client resolves a relative reference against the target URL of the request that received that response. If it follows another redirect, the new request URL becomes the base for the next response.

Suppose the request URL is:

https://api.example.test/v1/jobs/42

These Location values resolve differently:

Location valueResolved destinationExplanation
https://files.example.test/results/42https://files.example.test/results/42An absolute URL supplies its own scheme and host.
/results/42https://api.example.test/results/42A root-relative path starts at the origin’s root.
../results/42https://api.example.test/v1/results/42A path-relative reference is resolved from the base path’s directory.
//files.example.test/results/42https://files.example.test/results/42A network-path reference inherits the scheme but replaces the host.

The last path segment of the base matters. With /v1/jobs/42, the base directory is /v1/jobs/. A trailing slash changes the result: resolving ../results/42 against /v1/jobs/42/ instead yields /v1/jobs/results/42.

A query-only reference such as ?page=2 keeps the base path while replacing its query. Fragments are not sent in HTTP requests; redirect handling can also involve fragment inheritance. If your client exposes fragments to callers, include those cases in its compatibility tests rather than assuming ordinary URL joining covers every HTTP redirect rule.

Advertisement

Run a controlled local test

The following Python standard-library example starts a server on an ephemeral loopback port. It returns three redirects from the same request path, resolves each Location against that request’s URL, and then requests the resolved destination. It disables automatic redirects so the test can inspect the header first.

Save this as test_location.py and run python3 test_location.py. It needs no third-party packages. The local test intentionally uses HTTP; that is not a recommendation to send credentials over HTTP.

from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
from urllib.error import HTTPError
from urllib.parse import parse_qs, urljoin, urlsplit
from urllib.request import HTTPRedirectHandler, ProxyHandler, build_opener


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        request = urlsplit(self.path)

        if request.path == "/v1/jobs/42":
            case = parse_qs(request.query).get("case", [""])[0]
            port = self.server.server_address[1]
            locations = {
                "absolute": f"http://127.0.0.1:{port}/results/42",
                "root": "/results/42",
                "path": "../results/42",
            }
            if case not in locations:
                self.send_error(400, "Unknown test case")
                return
            self.send_response(302)
            self.send_header("Location", locations[case])
            self.end_headers()
            return

        if request.path in ("/results/42", "/v1/results/42"):
            self.send_response(204)
            self.end_headers()
            return

        self.send_error(404)


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


server = HTTPServer(("127.0.0.1", 0), Handler)
thread = Thread(target=server.serve_forever)
thread.start()

try:
    port = server.server_address[1]
    origin = f"http://127.0.0.1:{port}"
    opener = build_opener(ProxyHandler({}), NoRedirect())
    expected_paths = {
        "absolute": "/results/42",
        "root": "/results/42",
        "path": "/v1/results/42",
    }

    for case, expected_path in expected_paths.items():
        request_url = f"{origin}/v1/jobs/42?case={case}"
        try:
            with opener.open(request_url, timeout=3):
                raise AssertionError("Expected a redirect response")
        except HTTPError as response:
            try:
                if response.code != 302:
                    raise AssertionError(f"Unexpected status: {response.code}")
                location = response.headers.get("Location")
                if location is None:
                    raise AssertionError("Missing Location header")
            finally:
                response.close()

        destination = urljoin(request_url, location)
        if destination != origin + expected_path:
            raise AssertionError(f"Unexpected destination: {destination}")

        with opener.open(destination, timeout=3) as response:
            if response.status != 204:
                raise AssertionError(f"Unexpected status: {response.status}")
        print(f"{case}: resolved and reached the expected local path")
finally:
    server.shutdown()
    thread.join()
    server.server_close()

The assertions express the expected behavior; the printed lines are not recorded test results. Add equivalent cases to your client’s own test suite, using its HTTP library and redirect settings. Test missing and malformed Location values, trailing slashes, query-only references, network-path references, and multi-hop redirects. Also test the status codes your client supports: redirect status can affect whether a request method and body are preserved, so do not assume every redirect behaves like this GET example.

The local server’s 204 responses check reachability for these specific destinations during the test. URL resolution alone cannot tell you whether a service exists, whether a request will succeed, or whether the service is trustworthy.

Advertisement

Validate destinations before following redirects

A server can return an absolute Location or a //host/path reference that points somewhere other than the original API. Redirects may be legitimate—for example, to a separately hosted resource—but automatically forwarding credentials to the new destination can expose them.

For each redirect, use a policy appropriate to the integration:

  1. Resolve the reference against the current request URL, then parse the result. Reject invalid URLs and schemes your client does not permit; require HTTPS for sensitive production traffic unless there is a documented exception.
  2. Reject embedded user information such as user:password@host. Compare the resolved scheme, host, and effective port against an explicit destination policy. Be deliberate about normalization and default ports.
  3. Do not automatically carry Authorization, API keys, cookies, or other sensitive headers to a different origin. Review the HTTP library’s redirect and cookie behavior, including headers it adds automatically. Only send credentials to destinations explicitly authorized to receive them.
  4. Apply the same checks at every hop, with a redirect limit and timeouts. Treat a missing, invalid, or disallowed Location as an error rather than silently continuing.

A host allowlist is useful but is not a complete defense when an application fetches URLs influenced by untrusted users. In that setting, also restrict loopback, private, link-local, and other prohibited addresses as appropriate; account for DNS resolution and rebinding; revalidate redirects; and enforce network egress restrictions. Bound response sizes and other resource consumption, and require authorization for the fetching feature. A hostname check or URL parser alone cannot enforce those boundaries.

Reverse proxies and deployment checks

A reverse proxy can expose an API under a public host or path prefix while the upstream application sees a different host, scheme, or path. A root-relative Location is resolved at the public origin’s root, which may omit a proxy’s external path prefix. An absolute Location generated from internal request details may instead point clients at an internal hostname or an unexpected scheme.

Test redirects through the same public-facing proxy configuration that production clients use, not only against the upstream application. Configure the application and proxy to agree on the external origin and path; trust forwarded host and scheme information only from controlled proxies. Clients should still validate the final destination, because correct proxy configuration is not a substitute for client-side credential policy.

Common Mistakes

  • Joining against the API base: Use the URL of the request that received the response. A nested path or earlier redirect can make the results differ.
  • Concatenating strings: Adding the Location text to a hostname does not correctly handle .., queries, or network-path references. Use a URI-reference resolution API, then test its behavior.
  • Assuming relative means same host: //other.example/path is relative to the scheme but changes the authority.
  • Testing only parsing: A parsed URL may be unreachable or disallowed. Test resolution, policy decisions, and actual requests separately.
  • Forgetting the HTTP library: Automatic redirect handling may happen before application code sees the response. Verify how your chosen library handles methods, bodies, cookies, and sensitive headers.

Best Practices

Keep redirect test cases in release checks for each supported client environment. Include same-origin and cross-origin destinations, path-prefix proxy deployments, redirect loops, and a destination that policy rejects. Use disposable credentials or no credentials in tests, and ensure failure messages do not reveal secrets.

For debugging, record the status, sanitized request URL, sanitized Location value, resolved destination, and policy decision. Remove user information, tokens, and sensitive query values before logging.

Conclusion

Resolve each Location reference against the request URL that produced it, then validate the destination before following it or forwarding credentials. A local redirect test catches resolution errors; deployment and security tests establish whether the resulting requests are appropriate.

What would your domain sell for?

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