Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect HTTP or HTTPS then force HTTPS in JavaScript

Is there any way to detect HTTP or HTTPS and then force usage of HTTPS with JavaScript?

I have some codes for detecting the HTTP or HTTPS but I can't force it to use https: .

I'm using the window.location.protocol property to set whatever the site is to https: then refresh the page to hopefully reload a new https'ed URL loaded into the browser.

if (window.location.protocol != "https:") {    window.location.protocol = "https:";    window.location.reload(); } 
like image 510
Registered User Avatar asked Jan 18 '11 10:01

Registered User


People also ask

Should I force redirect to HTTPS?

Without SSL, your website will show insecure to the visitors. Therefore, using an SSL-encrypted connection for safety, accessibility or PCI compliance reasons is necessary. It becomes very important to redirect from HTTP to HTTPS.

Do browsers automatically redirect HTTPS?

In its default configuration, without explicit action by the user or the web site, no major browsers would automatically use HTTPS. If you redirect HTTP to HTTPS, make sure to mark your cookies as secure so you don't leak them in the initial accesses through http.

How do I know HTTP or HTTPS?

If the URL has http:// at the beginning, you are accessing it via HTTP. Likewise for https:// .


2 Answers

Try this

if (location.protocol !== 'https:') {     location.replace(`https:${location.href.substring(location.protocol.length)}`); } 

location.href = blah adds this redirect to the browser history. If the user hits the back button, they will be redirected back to the the same page. It is better to use location.replace as it doesn't add this redirect to the browser history.

like image 194
Soumya Avatar answered Sep 23 '22 16:09

Soumya


Setting location.protocol navigates to a new URL. No need to parse/slice anything.

if (location.protocol !== "https:") {   location.protocol = "https:"; } 

Firefox 49 has a bug where https works but https: does not. Said to be fixed in Firefox 54.

like image 27
sam Avatar answered Sep 20 '22 16:09

sam