php实现301重定向
使用header函数实现301重定向
在PHP中,可以通过header函数发送HTTP头部实现301永久重定向。确保在调用header函数之前没有输出任何内容,否则会导致错误。
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://www.newdomain.com/newpage.php");
exit();
通过.htaccess文件实现301重定向
对于Apache服务器,可以在.htaccess文件中添加重定向规则。这种方法不需要修改PHP代码,性能更好。
Redirect 301 /oldpage.php https://www.newdomain.com/newpage.php
或者使用mod_rewrite模块:
RewriteEngine On
RewriteRule ^oldpage\.php$ https://www.newdomain.com/newpage.php [R=301,L]
WordPress中的301重定向
在WordPress中,可以通过主题的functions.php文件添加重定向代码:
add_action('template_redirect', 'custom_redirect');
function custom_redirect() {
if (is_page('old-page')) {
wp_redirect('https://www.newdomain.com/new-page', 301);
exit;
}
}
批量处理301重定向
当需要处理多个URL重定向时,可以创建一个重定向映射数组:
$redirects = [
'/old-url1' => '/new-url1',
'/old-url2' => '/new-url2'
];
$request_uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
if (array_key_exists($request_uri, $redirects)) {
header("HTTP/1.1 301 Moved Permanently");
header("Location: " . $redirects[$request_uri]);
exit();
}
注意事项
确保在header重定向后调用exit()或die()函数,防止脚本继续执行。使用301重定向会影响SEO,搜索引擎会将旧URL的权重传递给新URL。测试重定向是否生效可以使用在线HTTP头检查工具或curl命令:
curl -I http://yourdomain.com/oldpage






