301或302使用PHP重定向

too*_*les 62 php

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

有没有办法向搜索引擎显示正确的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');
};
Run Code Online (Sandbox Code Playgroud)

dyn*_*mic 124

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

header('Location: http://www.yoursite.com/home-page.html');
// OR: header('Location: http://www.yoursite.com/home-page.html', true, 302);
exit;
Run Code Online (Sandbox Code Playgroud)

如果你需要永久重定向,又名:301 Moved Permanently,做:

header('Location: http://www.yoursite.com/home-page.html', true, 301);
exit;
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看PHP手册以获取标题功能Doc.另外,exit;使用时不要忘记打电话header('Location: ');

但是,考虑到您正在进行临时维护(您不希望搜索引擎将您的页面编入索引),建议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>
Run Code Online (Sandbox Code Playgroud)

  • 语法是`void header(string $ string [,bool $ replace = true [,int $ http_response_code]])` - http://php.net/manual/en/function.header.php (7认同)
  • OP在维护期间要求重定向,在这种情况下,他必须使用302而不是301进行临时重定向.如果301也称为永久重定向,浏览器将永远不会尝试该页面,而是转到重定向的页面. (3认同)
  • @michaeld永远不要将占位符代码测试为生产代码.在答案中使用什么示例URL无关紧要 - 在运行代码之前,您应该始终在其位置替换您自己的已知URL. (3认同)

Vit*_*min 17

以下代码将发出301重定向.

header('Location: http://www.example.com/', true, 301);
exit;
Run Code Online (Sandbox Code Playgroud)


bin*_*nar 7

从PHP或htaccess开始,我认为你的工作方式并不重要.两者都将完成同样的事情.

我想指出的一件事是你是否希望搜索引擎在这个"维护"阶段开始索引你的网站.如果没有,您可以使用状态代码503("暂时关闭").这是一个htaccess示例:

RewriteEngine on
RewriteCond %{ENV:REDIRECT_STATUS} !=503
RewriteCond %{REMOTE_HOST} ^192\.168\.0\.1
ErrorDocument 503 /redirect-folder/index.html
RewriteRule !^s/redirect-folder$ /redirect-folder [L,R=503]
Run Code Online (Sandbox Code Playgroud)

在PHP中:

header('Location: http://www.yoursite.com/redirect-folder/index.html', true, 503);
exit;
Run Code Online (Sandbox Code Playgroud)

使用您正在使用的当前PHP重定向代码,重定向是302(默认).