Reputation: 41219
How can I redirect the following url in javascript :
http://example.com/?querystrings
=>
http://www.example.com
I want to redirect my url without www to www discarding the querystrings.
I know how to do it server side using mod_rewrite, I am working on a client side js app, where I need this.
Is this type of redirection possible with JS?
My code so far :
<body onload="addwww()">
<script>
function addwww() {
location.href="http://www.example.com";
}
</script>
it redirects the entire page to www with redirect loop error. how can I redirect only when there is no www in the url?
Thanks!
Upvotes: 0
Views: 1623
Reputation: 49
This script replace non-www to www:
if(!/\.?www./g.test(location.host)) {
location.href = location.href.replace("://","://www.")
}
Upvotes: 3
Reputation: 1709
Use regexp to identify www
:
if (!(/www/.test(location.href)))
location.href = 'http://www.example.com';
Upvotes: 1
Reputation: 901
As mentioned in the comment, you may try something like
if (location.href.indexOf('www') < 0)
location.href = 'http://example.com';
or
if (!location.href.indexOf('http://www'))
location.href = 'http://example.com';
as a start.
Upvotes: 2