php实现重定向
使用header函数进行重定向
在PHP中,header()函数是实现重定向的常用方法。通过发送HTTP头信息Location,浏览器会自动跳转到指定URL。需确保在调用header()前没有输出任何内容(包括空格或HTML标签)。
<?php
header("Location: https://example.com");
exit(); // 确保后续代码不会执行
?>
延迟重定向
通过refresh头实现延迟跳转,适合需要显示提示信息的场景。

<?php
header("Refresh: 5; url=https://example.com");
echo "5秒后跳转到新页面";
?>
使用HTTP状态码
对于永久重定向(301)或临时重定向(302),可指定状态码:

<?php
header("Location: https://example.com", true, 301); // 301永久重定向
exit();
?>
通过HTML meta标签实现
如果无法使用header()(如已有输出),可通过HTML的meta标签实现:
<?php
echo '<meta http-equiv="refresh" content="0;url=https://example.com">';
?>
使用JavaScript重定向
适用于需要动态判断的场景:
<?php
echo '<script>window.location.href = "https://example.com";</script>';
?>
注意事项
- 确保
header()调用前无输出,否则会触发“headers already sent”错误。 - 重定向后建议使用
exit()或die()终止脚本执行。 - 对于SEO优化,优先使用301永久重定向。





