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(); }
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.
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.
If the URL has http:// at the beginning, you are accessing it via HTTP. Likewise for https:// .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With