怎么用php代码做301重定向? 打印

  • 0

当您的一个php网页不再继续使用时,可以用php代码设置301重定向,将这个页面重定向到其他的页面上去,代码如下:

<?php
// 请将下面的URL替换为您想要重定向到的网页的URL
$new_url = 'http://www.example.com/new-page';
// 发送301响应头
header('HTTP/1.1 301 Moved Permanently');
// 重定向到新网页
header('Location: '.$new_url);
// 结束脚本
exit;
?>

或者:

<?php
// Permanent 301 redirection
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://www.example.com/new-page");
exit();
?>

另外,请确保在发送响应头之前没有输出任何内容,否则可能会出现问题。如果您在脚本中使用了输出缓冲(output buffering),则需要在发送响应头之前调用ob_end_clean()函数清空输出缓冲区。例如:

<?php
// 清空输出缓冲区
ob_end_clean();
// 请将下面的URL替换为您想要重定向到的网页的URL
$new_url = 'http://www.example.com/new-page';
// 发送301响应头
header('HTTP/1.1 301 Moved Permanently');
// 重定向到新网页
header('Location: '.$new_url);
// 结束脚本
exit;
?>

示例代码中http://www.example.com/new-page就是重定向的目标网址,请将它修改为您自己的新网址。 用上面的代码替换掉不再使用的php页面代码,然后再访问该php页面就会跳转到重定向的网址上去了。

以上方法只适合单个或者少量PHP页面,要进行整个域名或者大量页面跳转还是用.htaccess设置重定向。


这篇文章对您有帮助吗?

« 返回

Powered by WHMCompleteSolution