301 跳转是一种 HTTP 状态码,表示请求的资源已经被永久移动到新的 URL。当服务器返回 301 状态码时,浏览器会自动将请求重定向到新的 URL。这种跳转对搜索引擎优化(SEO)非常有用,因为它可以保留旧页面的权重并传递给新页面。
在 PHP 中实现 301 跳转非常简单,可以使用 header
函数来发送 HTTP 头信息。
<?php
// 设置新的 URL
$newUrl = 'https://www.example.com/new-page.php';
// 发送 301 跳转头信息
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $newUrl);
// 结束脚本执行
exit();
?>
header
函数之前已经有任何输出(包括空格、换行等),PHP 会报错,提示头信息已经发送。解决方法是在调用 header
函数之前确保没有任何输出。<?php
ob_start(); // 开启输出缓冲
// 设置新的 URL
$newUrl = 'https://www.example.com/new-page.php';
// 发送 301 跳转头信息
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $newUrl);
// 结束脚本执行
exit();
?>
http://
或 https://
)。<?php
// 错误的 URL 格式
$newUrl = 'www.example.com/new-page.php'; // 缺少协议
// 正确的 URL 格式
$newUrl = 'https://www.example.com/new-page.php'; // 包含协议
?>
<?php
// 错误的重定向循环
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://www.example.com/a-page.php'); // A 页面重定向到 B 页面
exit();
// B 页面
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://www.example.com/a-page.php'); // B 页面重定向回 A 页面
exit();
?>
通过以上信息,你应该能够理解 PHP 301 跳转的基础概念、优势、类型、应用场景以及常见问题及解决方法。
领取专属 10元无门槛券
手把手带您无忧上云