簡體   English   中英

使用 PHP 進行 301 或 302 重定向

[英]301 or 302 Redirection With 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');
};

對於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;

有關更多信息,請查看頭函數Doc的 PHP 手冊。 另外,不要忘記調用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>

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

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

我認為從 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 (默認)。

你有沒有檢查你得到什么標題? 因為你應該得到302以上。

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

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

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

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

從 PHP文檔

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

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

將此文件保存在與 .htaccess 相同的目錄中

RewriteEngine on
RewriteBase / 

# To show 404 page 
ErrorDocument 404 /404.html

# Permanent redirect
Redirect 301 /util/old.html /util/new.php

# Temporary redirect
Redirect 302 /util/old.html /util/new.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM