301跳转是指当用户访问某个URL时,服务器会将请求永久重定向到另一个URL,并返回状态码301。该方式常用于网站URL结构调整、页面永久迁移,或者根据终端设备进行重定向。PHP中实现301跳转操作简单,灵活且高效。
在PHP中,可以通过header()函数发送HTTP响应头,将Location字段设置为目标URL,从而实现跳转。
header("Location: https://www.example.com/new-url", true, 301);
exit;
上面代码将访问者重定向到指定的URL,并返回301状态码。第二个参数true表示替换之前相同名称的header。
另一种方法是先调用http_response_code()设置状态码,再通过header()设置Location头。
http_response_code(301);
header("Location: https://www.example.com/new-url");
exit;
这种写法将状态码和跳转地址分开处理,逻辑更加清晰。
以下示例展示了两种实现301跳转的完整代码:
$url = "https://www.example.com/new-url";
// 方式一:header函数实现
header("Location: $url", true, 301);
exit;
// 方式二:http_response_code和header函数实现
http_response_code(301);
header("Location: $url");
exit;
调用header()之前,不能有任何页面输出,包括空格、换行或HTML标签。否则会导致跳转失败或警告。
// 错误示例
echo "Hello World!";
header("Location: https://www.example.com");
exit;
// 正确示例
header("Location: https://www.example.com");
exit;
如果使用http_response_code()设置状态码,必须在调用header()设置Location头之前完成。因为设置Location时,状态码会自动变为默认200。
// 错误示例
header("Location: https://www.example.com");
http_response_code(301);
exit;
// 正确示例
http_response_code(301);
header("Location: https://www.example.com");
exit;
PHP实现301跳转操作简单实用,无论是页面URL调整还是跨终端重定向,都能轻松应对。只需正确使用header()和http_response_code()函数,并确保无提前输出,即可保证跳转稳定可靠。