如何将一个URL重定向到另一个URL?

34

如何使用JavaScript在网页中将页面重定向到另一个URL?


1
你发送一个带有301或302状态码的HTTP Location头部。具体取决于你的Web服务器和/或服务器端编程环境。 - Quentin
7个回答

45
window.location.href = "URL2"

如果你确实希望在客户端上执行此操作,可以在页面的JS块或包含文件中执行;通常情况下,服务器会通过300系列的响应发送重定向。


使用这段代码,当我们访问URL2网页时会发生什么?我想要重定向网页如果用户加载了URL1 - return

26

你在问题标签中添加了javascripthtml...

对于一个纯粹的HTML解决方案,你可以在head标签中使用一个meta标签来“刷新”页面,指定不同URL:

<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.yourdomain.com/somepage.html">

如果您可以/希望使用JavaScript,您可以设置windowlocation.href

<script type="text/javascript">
    window.location.href = "http://www.yourdomain.com/somepage.html";
</script>

11

您可以通过JavaScript重定向一个或多个URL,只需使用简单的window.location.hrefif else

使用以下代码:

<script>
if(window.location.href == 'old_url')
{
    window.location.href="new_url";
}


//Another url redirect
if(window.location.href == 'old_url2')
{
    window.location.href="new_url2";
}
</script>

您可以通过这个步骤重定向许多URL。谢谢。


4
如果您想要重定向页面,只需要使用window.location。用法如下:
window.location = "http://www.redirectedsite.com"

3

1
location.href = "Pagename.html";

-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接