[英]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.