Absolute and relative URLs in HTML
When loading images and other assets in HTML — or more generally speaking, when referencing any resource in HTML — you can choose between various forms of absolute and relative URLs.
Here's a short overview of
- Absolute URLs, such as
https://example.org/img/logo.png
- Protocol-relative URLs, such as
//example.org/img/logo.png
- Root-relative URLs, such as
/img/logo.png
- Relative URLs, such as
img/logo.png
Absolute URLs
Example: https://example.org/img/logo.png
There's not a lot to say about absolute URLs. An absolute URL stands for itself, and browsers need no further context to resolve them.
Protocol-relative URLs
Example: //example.org/img/logo.png
Synonym: Scheme-relative URLs
In a protocol-relative URL, the author omits the schema part of the URL. Browsers interpret such URLs in the context of the HTML document referencing them. If the document is loaded via HTTP, HTTP is also used to load the sub-resource. If the document is loaded via HTTPS, HTTPS is used for the sub-resource as well.
Root-relative URLs
Example: /img/logo.png
Synonyms: Path-absolute URLs, host-relative URLs
Root-relative URLs omit not only the schema part, but also the host part. The significant piece of root-relative URLs is the leading slash "/". When resolving such URLs, browsers prepend the host and schema of the document's URL.
That means that when /img/logo.png
is a sub-resource of https://example.org/
, the browser resolves it to https://example.org/img/logo.png
. If a page deeper down the hierarchy of the website (e.g.https://example.org/blog/2020/05/04/a-blog-entry.html
) includes /img/logo.png
, the resolved URL of the resulting request is also https://example.org/img/logo.png
.
You can think of root-relative URLs as being relative to the root folder of the domain.
Relative URLs
Example: img/logo.png
Synonym: Path-relative URLs
The example looks quite similar to the root-relative one, but notice the missing slash "/" at the beginning. Browsers resolve such URLs relative to the loaded document. Using the example of root-relative URLs again, when img/logo.png
is a sub-resource of https://example.org/
, the browser resolves it to https://example.org/img/logo.png
. Mind that in this case, there's no difference between the root-relative and relative form. However, when https://example.org/blog/2020/05/04/a-blog-entry.html
references img/logo.png
, the browser attempts to load https://example.org/blog/2020/05/04/img/logo.png
.
It's pretty unlikely a website puts its logo into a location like https://example.org/blog/2020/05/04/img/logo.png
, by the way.
Conclusion
I have to admit I confused relative URLs and root-relative URLs for years. The need for using correct terms in tests of my site generator caused me to write down this overview. When starting a new site, I reach for root-relative URLs these days.
Further resources
If you want to know more about this stuff, have a look at these resources: