2012-02-20 64 views
43

我正在考慮在網站啓動階段使用以下代碼,向用戶展示維護頁面,同時向我展示網站的其餘部分。301或302使用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'); 
}; 
+11

記得在這些頭文件後退出你的腳本 – Vitamin 2012-02-20 15:43:34

回答

96

對於302 Found,即臨時重定向做:

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

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

header('Location: http://www.yoursite.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> 
+6

語法是'void header(string $ string [,bool $ replace = true [,int $ http_response_code]]) - http://php.net/manual /en/function.header.php – Vitamin 2012-02-20 15:41:04

+3

OP在維護期間要求重定向,在這種情況下,他必須使用302而不是301來臨時重定向。在301又名永久重定向的情況下,瀏覽器將永遠不會嘗試該頁面,而是轉到重定向頁面。 – seven 2014-02-11 17:50:45

+0

有沒有人會提到這個「yoursite.com」只是讓我的防病毒盾報告幾個「檢測到威脅」?爲什麼不在你的回答中使用example.com。請幫助我們,並將您的帖子更新到example.com,因爲yoursite.com是惡意軟件。當我測試你的代碼時,它會將我重定向到惡意軟件。泰爲正確的答案,但認真......修復這個跆拳道。 – 2017-05-10 08:04:53

3

你有沒有檢查你收到了什麼標題?因爲你應該得到一個302以上。

從手冊:http://php.net/manual/en/function.header.php

第二特例是在 「位置:」 首標。除非已經設置了201或3xx狀態碼,否則它不僅會將此標題發送回瀏覽器,還會向瀏覽器返回REDIRECT(302)狀態碼。

<?php 
header("Location: http://www.example.com/"); /* Redirect browser */ 

/* Make sure that code below does not get executed when we redirect. */ 
exit; 
?> 
3

從PHP documentation

第二個特殊情況是 「位置:」 頭。除非已經設置了201或3xx狀態碼,否則它不僅會將此標題發送回瀏覽器,還會向瀏覽器返回REDIRECT(302)狀態碼。

所以你已經在做正確的事情。

16

以下代碼將發出301重定向。

header('Location: http://www.example.com/', true, 301); 
exit; 
4

我不認爲它真的很重要你怎麼做,從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] 

在PHP:

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

隨着你使用當前的PHP重定向代碼,重定向是302(默認)。