Jeremy Davis
Jeremy Davis
Sitecore, C# and web development
Article printed from:

The power of relative URLs

Published 28 March 2014
Updated 25 August 2016
HTML ~1 min. read

Quick (and not Sitecore specific) one today, as I've got a very busy week in the office and it's eating into my time for blog posts. To make a break from a few weeks of writing about navigation patterns, here's an idea about something I've found a surprising number of developers don't know about: "Protocol agnostic" or "Schemeless" URLs.

[NB: It's been pointed out that in an ideal world, we'd all just use SSL for everything these days. I'm posting this on the assumption that I'm not the only dev who finds that the projects they work on can't always follow that approach]

It's commonly understood that you can write URL relative to the root of your website. When you render a link like this:

<a href="/folder/mypage.htm">link</a>


Web browsers interpret that by sticking the current protocol and domain onto the front of the path, in effect making it look like you wrote:

<a href="">link</a>


But what seems to be less well understood is that you can write relative URLs where all you miss out is the "HTTP:" bit:

<a href="//">link</a>


And here the web browser will just fill in the current protocol being used to render your page. This allows you to reference something external (A page, image, stylesheet or javascript file) and be confident that your user's browser won't throw any "Should I only load secure content?" error messages if the page gets switched between HTTP and HTTPS. You never want your internet users to see a message like these:

Insecure content

(Of course, if you use this approach to URLs then you need to have your web server configured with a valid SSL certificate so it can respond to HTTPS requests – but I figure you probably all knew that already)

I come across a surprising amount of code in the back end of web projects where developers are manually checking the current protocol so that they can re-write links to external resources like this when the site needs to switch to HTTPS. But by using the protocol agnostic version of the URL you can do away with that code entirely, and hence do away with the risk of it introducing bugs.

Now it's worth pointing out that this doesn't work in every scenario. IE7 and IE8 are commonly called out for incorrectly downloading resources with protocol agnostic URLs twice, so you might not want to take this approach if you site must support them. Also mail clients may not cope well with this approach to URLs: some versions of Outlook may hang. Hence this style of URL is probably not correct if you're writing code that's going in the body of an email.

But if your site is aimed at modern web browsers why not give it a try?

↑ Back to top