Just to add to alain34's solution; using window.location.protocol might make the code smaller and easier..
Main Topics
Browse All TopicsUsing JavaScript, I want to redirect to https://example.com/page if a page is accessed via http:// or using a subdomain.
So:
http://example.com/
Should be redirected to:
https://example.com/
https://www.example.com/
Should be redirected to:
https://example.com/
http://www.example.com/sub
Should be redirected to:
https://example.com/sub/di
... And so forth
This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.
Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.
If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.
Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.
Access the answers to your technology questions today.
30-day free trial. Register in 60 seconds.
Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Try it out and discover for yourself.
30-day free trial. Register in 60 seconds.
Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.
Thanks, that answers half my question. Subdomains should also be redirected.
http://www.example.com/sub
Should be redirected to:
https://example.com/sub/di
and
https://www.example.com/su
Should be redirected to:
https://example.com/sub/di
erm...
if (location.protocol != 'https') {
loc = "https://"
loc += (location.host.toLowerCase
location.replace(loc+'/'+l
}
yo
Hmmm, that does not work with www either. None of these test for www, just for https:
https://www.example.com/su
Should be redirected to:
https://example.com/sub/di
It does not work.
First I got an error so I added var loc; to the top but now my redirected urls look like this:
https://www.example.com/un
Business Accounts
Answer for Membership
by: alain34Posted on 2009-10-19 at 04:48:51ID: 25604270
Hello hankknight,
tring(0,7) == 'http://') { ring(7,win dow.locati on.href.le ngth);
Should do the trick
<html>
<head>
<script>
function redirect() {
if (window.location.href.subs
window.location = 'https://' + window.location.href.subst
}
}
</script>
<title>Test</title>
</head>
<body onload='redirect()'>
TEST
</body>
</html>
Regards,
alain34