Relative URLs

Published: Sun 30 July 2017
By EWS

In Blog.

One thing that I don't think is going to ever change in this domain is the fact that no matter how much you know, there's always something new to learn. Going back to basics every now-and-again is worthwhile, no matter how much of a seasoned player you may think you are.

Case-in-point (in my case, that is), and as background, URLs follow similar rules to file paths, that is:

  • href="../images/myimage.png" points to something adjacent to the page in-which it lies;
  • href="images/myimage.png points to a location below the page in-which it lies;

A little more URL-specific, but still well-within the domain of “intuitive” is the root-relative URL:

href="/images/myimage.png"

This points to a location one level below the root of a site. This type of reference is useful when you don't know where your current document lies in the hierarchy (if, for example, you're writing something in a scripting language or using a framework that will decide where the file will end up sometime down-the-line).

What I wasn't aware of (until now, of course) is the protocol-relative URL, of the form:

href="//bar.com/images/myimage.png"

When being referenced from foo.com in a manner similar to the following:

<head><title>This is https://Foo.com/</title></head>
<body>
<a href="//bar.com/images/myimage.png"/>
</body>

The reference will adopt the same protocol as the page from-which it's referenced, and therefore (in the above case), resolve to https://bar.com/images/myimage.png.

Whereas in the past, the value of protocol-relative URLs would have been debatable, with the modern expectation of everyone having a security certificate for their site, I could imagine this being used more often. A shout-out to this useful article for enlightening me.

Comments !

social