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

header("HTTP/1.1 301 Moved Permanently");
header("Location: https://www.newdomain.com/new-url");
exit();
确保在调用header()前没有输出内容,否则会报错。exit()用于终止脚本继续执行。
通过.htaccess文件
对于Apache服务器,可在.htaccess中添加规则:

Redirect 301 /old-page.html https://www.example.com/new-page.html
或使用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();
}
}
注意事项
- 301重定向会影响SEO,搜索引擎会将旧URL的权重转移到新URL
- 测试时建议先使用302临时重定向,确认无误后再改为301
- 确保重定向目标URL是绝对路径(包含协议和域名)
- 避免重定向循环(A→B→A的情况)






