php实现301重定向
PHP实现301重定向的方法
301重定向是一种永久性重定向,常用于网站URL结构调整或域名更换时保持SEO权重传递。以下是几种PHP实现301重定向的常见方式:
使用header()函数
通过PHP的header()函数发送HTTP状态码和Location头部实现重定向:

header("HTTP/1.1 301 Moved Permanently");
header("Location: https://newdomain.com/new-url");
exit();
直接设置状态码和Location
更简洁的写法,直接指定301状态码:
header("Location: https://newdomain.com/new-url", true, 301);
exit();
通过.htaccess文件实现
虽然不是纯PHP方案,但常与PHP项目配合使用:

Redirect 301 /old-page.php https://example.com/new-page.php
或使用mod_rewrite模块:
RewriteEngine On
RewriteRule ^old-url$ new-url [R=301,L]
WordPress中的实现
如果是WordPress站点,可在主题的functions.php中添加:
add_action('template_redirect', 'custom_301_redirect');
function custom_301_redirect() {
if (is_page('old-page')) {
wp_redirect('https://example.com/new-page', 301);
exit();
}
}
注意事项
- 必须在输出任何内容前调用
header()函数 - 重定向后务必使用
exit()或die()终止脚本执行 - 确保目标URL是完整绝对路径(包含http://或https://)
- 避免重定向循环(A→B→A的情况)
- 对于大量重定向,建议使用服务器配置(如.htaccess)而非PHP脚本
测试验证方法
- 使用浏览器开发者工具查看网络请求,确认返回状态码为301
- 通过在线HTTP头检查工具验证
- 检查搜索引擎是否已更新索引(可能需要数周时间)





