php实现域名跳转
PHP 实现域名跳转的方法
使用 header 函数进行 301 永久重定向
<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://www.newdomain.com");
exit();
?>
这种方法适用于 SEO 优化,告知搜索引擎该域名已永久迁移。
使用 header 函数进行 302 临时重定向
<?php
header("Location: https://www.newdomain.com");
exit();
?>
临时重定向适用于网站维护或临时更换域名的情况。
通过 .htaccess 文件实现跳转
RewriteEngine On
RewriteCond %{HTTP_HOST} ^olddomain\.com$ [NC]
RewriteRule ^(.*)$ https://www.newdomain.com/$1 [R=301,L]
这种方法直接在服务器层面实现跳转,效率更高。
使用 JavaScript 实现跳转
<?php
echo '<script>window.location.href = "https://www.newdomain.com";</script>';
?>
适用于需要在前端实现跳转的情况,但不利于 SEO。
带参数跳转的实现
<?php
$query_string = $_SERVER['QUERY_STRING'];
header("Location: https://www.newdomain.com?$query_string");
exit();
?>
保留原始 URL 的参数跳转到新域名。
根据请求路径跳转不同页面
<?php
$request_uri = $_SERVER['REQUEST_URI'];
if (strpos($request_uri, '/old-path') === 0) {
header("Location: https://www.newdomain.com/new-path");
} else {
header("Location: https://www.newdomain.com");
}
exit();
?>
实现基于路径的精细化跳转控制。
注意事项:
- 确保在调用 header 函数前没有输出任何内容
- 跳转后务必使用 exit 或 die 终止脚本执行
- 301 跳转会传递 SEO 权重,302 不会
- 大量跳转建议使用服务器配置实现







