php - 使用 PHP 进行 301 或 302 重定向

标签 php .htaccess redirect http-status-code-302

我正在考虑在网站启动阶段使用以下代码向用户显示停止维护页面,同时向我显示网站的其余部分。

有没有办法向搜索引擎显示正确的 302 重定向状态,或者我应该寻找另一种基于 .htaccess 的方法?

$visitor = $_SERVER['REMOTE_ADDR'];
if (preg_match("/192.168.0.1/",$visitor)) {
    header('Location: http://www.yoursite.com/thank-you.html');
} else {
    header('Location: http://www.yoursite.com/home-page.html');
};

最佳答案

对于 302 Found,即临时重定向:

header('Location: http://www.example.com/home-page.html');
// OR: header('Location: http://www.example.com/home-page.html', true, 302);
exit;

如果您需要永久重定向,也就是:301 Moved Permanently,请执行:

header('Location: http://www.example.com/home-page.html', true, 301);
exit;

欲了解更多信息,请查看 header function Doc 的 PHP 手册。 .另外,使用 header('Location: ');

时不要忘记调用 exit;

但是,考虑到您正在进行临时维护(您不希望搜索引擎索引您的页面),建议返回带有自定义消息的 503 Service Unavailable(即您不需要任何重定向):

<?php
header("HTTP/1.1 503 Service Unavailable");
header("Status: 503 Service Unavailable");
header("Retry-After: 3600");
?><!DOCTYPE html>
<html>
<head>
<title>Temporarily Unavailable</title>
<meta name="robots" content="none" />
</head>
<body>
   Your message here.
</body>
</html>

关于php - 使用 PHP 进行 301 或 302 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9363760/

相关文章:

.htaccess -> 域参数 -> https ://example. com/page 正在工作,而 https ://example. com/没有

php - mod_rewrite 从 .png 重定向到 .php

.htaccess - 使用 htaccess 强制 SSL 和 WWW 一起使用

Nginx -- 如果引用者,将 (x-forwarded-for) ip 添加到黑名单

php - 外部实体在 simplexml 中不起作用

php - SQL 数据库或文件系统中的照片 (2012)

php - Css 包括在 PHP 中实现 modrewrite 时不起作用

php - 清理 HTML 格式的内容以便在 Flash 中显示?

php - .htaccess 未重定向/to/index.php

javascript - 登录后无法重定向用户