Amit Verma
Amit Verma

Reputation: 41219

non-www to www client side redirection with javascript

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

Answers (3)

Jackson Santos
Jackson Santos

Reputation: 49

This script replace non-www to www:

if(!/\.?www./g.test(location.host)) {
    location.href = location.href.replace("://","://www.")
}

Upvotes: 3

Sudipta Kumar Maiti
Sudipta Kumar Maiti

Reputation: 1709

Use regexp to identify www:

if (!(/www/.test(location.href)))
     location.href = 'http://www.example.com';

Upvotes: 1

aliasm2k
aliasm2k

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

Related Questions