PHP 301 重定向

301 重定向用于将页面永久重定向到特定的 URL 或页面。主要用于改善 SEO。

301 是一种重定向类型的 HTTP 状态代码。

在 PHP 中,我们可以将 301 作为参数传递给 PHP 函数 header() 以永久重定向页面。

本教程演示如何使用 PHP 和 301 永久重定向页面。

使用 301 和 PHP header() 函数永久重定向到页面或 URL

我们可以通过几种方式使用 PHP header() 函数和 301 永久重定向到给定的 URL。

<?php
//Setting the HTTP status code first, then redirect.
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://www.delftstack.com/");
exit();
?>

这是一个简单的方法:

<?php
//We can also pass the HTTP status code 301 as a parameter in PHP `header()`.
header("Location: https://www.delftstack.com/",TRUE,301);
?>

PHP 还有一个设置 HTTP 状态码 http_response_code() 的功能;我们可以使用这个函数然后重定向,这也将是一个 301 重定向。参见示例:

<?php
http_response_code(301);
header('Location: https://www.delftstack.com/');
exit;
?>

上面所有三个代码都有相同的输出,它会将域永久重定向到我们的站点 https://www.delftstack.com/

首先,我们用上面的代码运行 index.php,它会重定向到我们的网站 https://www.delftstack.com/,然后我们在 index.php 中注释代码并再次运行它。

我们将看到 index.php URL 永久设置为 https://www.delftstack.com/

输出:

PHP 301 重定向