开发者

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.hre开发者_StackOverflowf("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)?


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;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜