2

I have a web page that is routed with https and all works well. I noticed I could change it to http and the page still loaded.

I am trying to check the window url and make it https if it was entered as http. Only for this page and with Jquery or Javascript. ( I know most would recommend not using a script for security )

This isn't working for me:

<script>
var url = window.location.pathname;
if url.match('^http://')
{
url = url.replace(/^http:\/\//, 'https://');
    window.location.pathname = url;
}

Thank you

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
DDDD
  • 3,790
  • 5
  • 33
  • 55
  • 10
    You should be doing this server-side. – Joseph Silber Sep 13 '13 at 01:52
  • 3
    That might not be working for you because you’re missing parentheses around the `if`’s condition. I’m pretty sure that’s at least one part of it. But yes, do it server-side. – Ry- Sep 13 '13 at 01:53
  • Should be done using .htaccess. See http://stackoverflow.com/questions/13977851/htaccess-redirect-to-https-www – Ayush Sep 13 '13 at 01:54
  • 1
    `window.location.pathname` returns the path in the URL after the `.tld`. You want to use `window.location.protcol`. But even then, this type of operation is best done in .htaccess. – honyovk Sep 13 '13 at 02:05
  • Would a CSRF or XSS be able to put this as a script and have it work? – DDDD Sep 13 '13 at 02:07
  • possible duplicate of [Detect HTTP or HTTPS then force HTTPS in JavaScript](http://stackoverflow.com/questions/4723213/detect-http-or-https-then-force-https-in-javascript) – Ja͢ck Sep 13 '13 at 02:31
  • Related: [Is redirecting http to https a bad idea?](http://stackoverflow.com/questions/4365294/is-redirecting-http-to-https-a-bad-idea) – Ja͢ck Sep 13 '13 at 02:34

1 Answers1

2

If you really want to do it client side:

<script>

   if (  window.location.protocol != 'https:' ) {
           window.location = document.URL.replace("http://","https://");
    }

</script>
Avitus
  • 15,640
  • 6
  • 43
  • 53
  • 1
    You should anchor your expression lest it replace `http://` anywhere in the URL, i.e. `/^http:\/\//`. – Ja͢ck Sep 13 '13 at 02:29
  • Exactly. Or use substring like this one http://stackoverflow.com/questions/4723213/detect-http-or-https-then-force-https-in-javascript – Matthew Lock Mar 14 '14 at 01:33