[英]Correct PHP for a 404 redirect?
我必須使用自定義404頁面進行url重定向(.htaccess不是一個選項)。 我正在考慮使用下面的代碼。 我正在嘗試通過向URL添加標志來考慮有效的重定向以及未找到頁面的真實情況。 你怎么看?
<?php
// check GET for the flag - if set we've been here before so do not redirect
if (!isset($_GET['rd'])){
// send a 200 status message
header($_SERVER['SERVER_PROTOCOL'] . ' 200 Ok');
// redirect
$url = 'new-url/based-on/some-logic.php' . '?rd=1';
header('Location: ' . $url);
exit;
}
// no redirection - display the 'not found' page...
?>
<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<h1>404:</h1>
<h3>Sorry, the page you have requested has not been found.</h3>
</body>
</html>
編輯 -之所以不能選擇.htaccess是因為我沒有apache在IIS6上運行。
添加404 標頭生成:
...
header("HTTP/1.0 404 Not Found");
// for FastCGI: header("Status: 404 Not Found");
// no redirection - display the 'not found' page...
?>
...
並刪除200個代碼:
// delete this line
header($_SERVER['SERVER_PROTOCOL'] . ' 200 Ok');
// because code should be 302 for redirect
// and this code will be generated with "Location" header.
如果我沒弄錯,您希望顯示404頁面的頁面,即不再存在的頁面。
據我所知(可能不會太多),如果沒有.htaccess或apache conf文件,您不能僅將php頁面設置為404處理程序。
我記得的是404.shtml是普通apache設置中404處理程序的默認文件,因此您需要將代碼放在該頁面中,
而且由於您無法使用.htaccess並且頁面為SHTML,因此無法將php放入其中,因此您可以使用從404.shtml到404.php的Javascript重定向,
希望能有所幫助。
您似乎不想重定向,但要包含相關頁面。 重定向不是必需的。 實際上,將apache 404錯誤處理程序用於漂亮的URL會破壞它。
以下示例腳本確實首先將請求解析為(相對)文件名模塊。 在您的代碼中,將是new-url/based-on/some-logic.php
或類似代碼。
緊接着,如果未找到模塊,則將使用錯誤頁面模板。 我將其命名為error404.php
因此您還需要創建該文件。
最后,即使找不到錯誤模板,也將返回標准的404錯誤消息。
<?php
// === resolver ===
// put your logic in here to resolve the PHP file,
// return false if there is no module for the request (404).
function resolveModule() {
// return false;
return 'new-url/based-on/some-logic.php';
}
// returns the filename of a module
// or false if things failed.
function resolveFile($module) {
$status = 200;
if (false === $module) {
$status = 404;
$module = 'error404.php';
}
// modules are files relative to current directory
$path = realpath($module);
if (!file_exists($path)) {
// hard 404 error.
$status = 404;
$path = false;
}
return array($path, $status);
}
// process the input request and resolve it
// to a file to load.
$module = resolveModule();
list($path, $status) = resolveFile($module);
// === loader ===
// send status message
header($_SERVER['SERVER_PROTOCOL'] . ' ' . $status, true, $status);
if (false !== $path) {
include($path); // include module file (instead of redirect)
} else {
// hard 404 error, e.g. the error page is not even found (misconfiguration)
?>
<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<h1>404:</h1>
<h3>Sorry, the page you have requested has not been found.</h3>
<p>Additionally the good looking error page is not available, so it looks really sad.</p>
</body>
</html>
<?
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.