页面使用Javascript重定向路径

时间:2013-11-19 16:42:04

标签: javascript

如何使用带路径的Javascript重定向请求?

my-domain.com/abc to www.other-domain.com/abc

其中'abc'是请求路径。还可以转发查询参数和片段标识符吗?

4 个答案:

答案 0 :(得分:1)

这应该在服务器端完成,但如果你想用javascript做,你可以做

location.href = location.href.replace(/(https?:\/\/)[^/]+/,'$1'+'www.other-domain.com');

注意:正则表达式包括使用与URL相同的协议转发..如果您不包含协议,它将尝试重定向到与该页面相同的域,但使用'www.other-domain.com/ ..'作为相对路径。所以你必须包括协议。作为替代方案,您可以像这样硬编码:

location.href = location.href.replace(/(https?:\/\/)[^/]+/,'http://www.other-domain.com');

答案 1 :(得分:0)

这可以解决您的问题,但强烈建议您在服务器级别完成。

window.location = 'www.other-domain.com' + (location.pathname + location.search);

答案 2 :(得分:0)

类似的东西:

var url = "http://www.other-domain.com" + location.path + location.search + location.hash;
location.href = url;

了解更多信息:http://www.w3schools.com/jsref/obj_location.asp

答案 3 :(得分:0)

window.location.replace("http://www.other-domain.com/abc");

有关详细信息,请参阅Window.location - Web API interfaces | MDN