How Relative URLs Are Resolved
Understand how browsers resolve relative URLs against a base URL, the rules for dot segments (../ and ./), protocol-relative URLs, and the HTML base element.
Detailed Explanation
Relative URL Resolution
Relative URLs are URLs that don't include a full scheme and hostname. They are resolved against a base URL to produce an absolute URL.
Types of Relative References
Given a base URL of https://example.com/blog/posts/page.html:
| Relative URL | Resolved Absolute URL |
|---|---|
other.html |
https://example.com/blog/posts/other.html |
./other.html |
https://example.com/blog/posts/other.html |
../index.html |
https://example.com/blog/index.html |
../../about.html |
https://example.com/about.html |
/absolute/path |
https://example.com/absolute/path |
//cdn.example.com/lib.js |
https://cdn.example.com/lib.js |
?q=test |
https://example.com/blog/posts/page.html?q=test |
#section |
https://example.com/blog/posts/page.html#section |
Resolution Algorithm
The browser follows RFC 3986 to resolve relative references:
- If the reference has a scheme (
https://), use it as-is (it is already absolute) - If the reference starts with
//, inherit the scheme from the base - If the reference starts with
/, replace the entire path - Otherwise, merge the reference with the base path
- Remove dot segments (
.and..) from the result
Using the URL Constructor
// The second argument is the base URL
new URL("../api/data", "https://example.com/app/page").href
// "https://example.com/api/data"
new URL("/assets/logo.png", "https://example.com/app/page").href
// "https://example.com/assets/logo.png"
new URL("?tab=settings", "https://example.com/app/page").href
// "https://example.com/app/page?tab=settings"
The <base> Element
HTML's <base> tag changes the base URL for all relative references in the document:
<head>
<base href="https://cdn.example.com/assets/">
</head>
<body>
<!-- Resolves to https://cdn.example.com/assets/images/logo.png -->
<img src="images/logo.png">
</body>
Protocol-Relative URLs (Deprecated)
URLs starting with // inherit the current page's protocol:
<!-- If page is https, loads https://cdn.example.com/lib.js -->
<script src="//cdn.example.com/lib.js"></script>
This pattern is now considered deprecated. Always use https:// explicitly.
Use Case
Understanding relative URL resolution is critical when building websites with nested route structures, working with HTML email templates, configuring reverse proxies, or migrating content between domains. Incorrect relative paths are a common source of broken images, missing stylesheets, and failed API calls after deployment.