Thomaszter
Thomaszter

Reputation: 1474

how to handle javascript redirect correctly?

When a user goes to the base domain http://www.domain.com/ or http://domain.com/,
the page has to be redirected to http://www.domain.com/#!/news.html

I mean something like this:

if (window.location.href("http://www.domain.com/") || window.location.href("http://domain.com/")) {
    window.location.replace("http://domain.com/#!/news.html");
}

This won't work. Especially, the page is provided on two different domains.
any ideas how to solve it in pretty Javascript or jQuery (using jQuery 1.4.2)?

Upvotes: 1

Views: 952

Answers (2)

bobince
bobince

Reputation: 536519

Use the parsed-URL properties on location, like pathname, hostname, search and hash rather than trying to mess with the href:

if (location.pathname==='/' && location.hash==='')
    location.hash= '#!/news.html';

Especially, the page is provided on two different domains.

It's best for SEO to put your site on only one particular hostname, and redirect any other associated hostnames to that canonical hostname. Let the HTTPD config worry about domains instead of your app. For example if you chose www.domain.com to be your canonical hostname, in Apache config you could say:

<VirtualHost *:80>
    ServerName www.domain.com
    DocumentRoot ...
    ... other settings for the main site ...
</VirtualHost>

<VirtualHost *:80>
    ServerName domain.com
    ServerAlias someotherdomain.org
    ServerAlias www.someotherdomain.org
    Redirect permanent / http://www.domain.com/
</VirtualHost>

Other web servers have a different ways of setting up redirects. If you have no access to the Apache config and you're limited to .htaccess (ugh) then you'd have to use mod_rewrite to do a conditional redirect based on the hostname.

Upvotes: 3

user372551
user372551

Reputation:

var loc =  window.location.href;

if(loc == 'http://domain.com' || loc == 'http://www.domain.com') {
  window.location.href = 'http://domain.com/#!/news.html';
}

Edit :

var d   = window.location.hostname;
var loc = window.location.href;
if(loc == d) { 
  window.location.href = d +'/#!/news.html';
}

document.domain really saved my life to answer your question, I tried to answer your question using regular expression, my patterns failed to match the available possibilities. seems like I really need to get back to learn regex :)

Edit :

var d = window.location.hostname;

Upvotes: 4

Related Questions