Web development tip: URLs that are relative to the protocol
Posted: (EET/GMT+2)
If you are developing web sites with ASP.NET (or otherwise) that support both regular http browsing and secured https browsing (for instance, a regular web site with a secured shopping portion), you might find this tip useful.
When creating links between pages (and/or to different applications within the site), you should not use absolute links in pages that might be downloaded with the https protocol. For instance, if you have a secured page (say, the order page) and that page contains absolute links to images and/or other parts of the application, user's browser can give a warning to the user about mixed content. For instance, IE displays something like "Only secure content is displayed. … [Show all content]".
To avoid this situation, you could easily use relative links. However, this isn't always easy, as you might need to link to other sites or content that you don't host on the same server. In this case, using absolute links might be the only option, but this requires you to specify the protocol (http/https). If you wanted to keep your current protocol, what options would you have?
From a programming perspective, you could simply create a helper function that looks at the current request (as in ASP.NET and C#, the Request.Protocol property) and create an on-the-fly link based on this information. I've done this myself, but there's a neater solution available as well. Enter protocol-relative URLs.
These protocol-relative URLs are specified in RFC 3986 section 4.2 and look like this:
//domain.com/path/file.aspx
Note the two slashes in the beginning and no protocol in the beginning (or in RFC terms, no scheme in the beginning). This might look a bit strange at first, but works fine in all major browsers; it is technically called a relative reference. With URLs like this, the problem of using the current (based on the page/view that is being loaded) protocol in your links is solved.
Happy hacking!
PS. In RFC terminology, I should be talking about schemes, URIs and relative references. I'm using here the terminology that is commonly used in ASP.NET development for simplicity's sake.