正确的404重定向PHP?

| 我必须使用自定义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的原因是因为我在IIS6上没有apache运行。     
已邀请:
        添加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的Java脚本重定向, 希望能有所帮助。     
        看来您不想重定向,但要包含有问题的页面。重定向不是必需的。实际上,将apache 404错误处理程序用于漂亮的URL会破坏。 以下示例脚本确实首先将请求解析为(相对)文件名模块。在您的代码中将是
new-url/based-on/some-logic.php
或类似的字符。 紧接着,如果未找到模块,则将使用错误页面模板。我将其命名为“ 4”,因此您还需要创建该文件。 最后,即使找不到错误模板,也将返回标准的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>
<?
}
    

要回复问题请先登录注册