在网站开发过程中,有时需要将用户从旧域名跳转到新域名,或者从不同页面跳转到特定的PHP页面。以下是使用PHP实现域名跳转的实例,通过表格形式展示具体步骤和代码。
| 步骤 | 说明 | 代码示例 |
|---|---|---|
| 1 | 创建一个PHP文件,例如`redirect.php`。 | ` |
| 2 | 获取当前域名。 | `$_SERVER['HTTP_HOST'];` |
| 3 | 设置目标域名。 | `$targetDomain='www.example.com';` |
| 4 | 判断当前域名是否为目标域名。 | `if($_SERVER['HTTP_HOST']!=$targetDomain):` |
| 5 | 使用header函数进行跳转。 | `header('Location:http://'.$targetDomain.$_SERVER['REQUEST_URI']);` |
| 6 | 输出结束标记,避免输出其他内容。 | `exit();` |
| 7 | 结束PHP代码。 | `?>` |
具体代码如下:

```php
$targetDomain = 'www.example.com';
if ($_SERVER['HTTP_HOST'] != $targetDomain) {
header('Location: http://'.$targetDomain.$_SERVER['REQUEST_URI']);
exit();
}
>
```
将以上代码保存为`redirect.php`,然后将该文件放置在需要跳转的旧域名下。当用户访问旧域名时,系统会自动跳转到新域名。









