Seth Petry-Johnson
Seth Petry-Johnson

Reputation: 12085

Combine explicit protocol specification with relative URL

I have a page that is accessed via HTTP. This page links to another page on the same server using HTTPS. What is the most elegant way, using HTML and/or Javascript, to force a transition to HTTPS while using a relative URL?

Basically, I want the opposite of a protocol-relative URL. I want to explicitly specify HTTPS WITHOUT hardcoding the hostname into the URL.

I'm working on a large legacy site so a solution using unobtrusive javascript with minimal changes to existing markup is ideal.

I realize that enforcing HTTPS is better performed at the destination page, but that isn't an option in this case.

Upvotes: 2

Views: 703

Answers (2)

Pointy
Pointy

Reputation: 413709

I think you're going to have to build the URL yourself from the pieces on window.location.

var path = anchor.href;

var httpsUrl = "https://" + 
  window.location.host + 
  (path.charAt(0) === '/' ? path : window.location.pathname + '/' + path);

or something like that (esp. if there's are parameters etc).

edit — it's been noted that modern browsers will give back the complete URL when you access the "href" value, making this an even easier problem to solve in those cases (as you just have to fix the protocol prefix). (Thanks @Daniel!)

Upvotes: 0

Cristian Sanchez
Cristian Sanchez

Reputation: 32107

$("a").each(function () { 
    this.href = "https://" + window.location.host + this.pathname + this.search + this.hash;
});

You could provide a more specific selector to make sure it doesn't mess up any links you didn't intend to change, but I leave that up to you since you know the requirements.

Upvotes: 2

Related Questions