[英]How to create an error 404 page using PHP?
我的文件.htaccess
处理从/word_here
到我的内部端点/page.php?name=word_here
所有请求。 PHP 脚本然后检查请求的页面是否在其页面数组中。
如果没有,我如何模拟错误 404?
我试过这个,但它没有导致我通过.htaccess
ErrorDocument
配置的 404 页面显示出来。
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
我是否认为重定向到错误 404 页面是错误的?
生成 404 页面的最新答案(从 PHP 5.4 或更高版本开始)是使用http_response_code
:
<?php
http_response_code(404);
include('my_404.php'); // provide your own HTML for the error page
die();
die()
不是绝对必要的,但它可以确保您不会继续正常执行。
您所做的将起作用,浏览器将收到 404 代码。 它不会做的是显示您可能期望的“未找到”页面,例如:
在此服务器上找不到请求的 URL /test.php。
那是因为当 PHP 返回 404 代码时,Web 服务器不会发送该页面(至少 Apache 不会)。 PHP 负责发送它自己的所有输出。 所以如果你想要一个类似的页面,你必须自己发送 HTML,例如:
<?php
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
include("notFound.php");
?>
您可以将 Apache 配置为对其自己的 404 消息使用相同的页面,方法是将其放在 httpd.conf 中:
ErrorDocument 404 /notFound.php
尝试这个:
<?php
header("HTTP/1.0 404 Not Found");
?>
通过 .htaccess 文件创建自定义错误页面
1. 404 - 页面未找到
RewriteEngine On
ErrorDocument 404 /404.html
2. 500 - 内部服务器错误
RewriteEngine On
ErrorDocument 500 /500.html
3. 403 - 禁止
RewriteEngine On
ErrorDocument 403 /403.html
4. 400 - 错误的请求
RewriteEngine On
ErrorDocument 400 /400.html
5. 401 - 需要授权
RewriteEngine On
ErrorDocument 401 /401.html
您还可以将所有错误重定向到单个页面。 喜欢
RewriteEngine On
ErrorDocument 404 /404.html
ErrorDocument 500 /404.html
ErrorDocument 403 /404.html
ErrorDocument 400 /404.html
ErrorDocument 401 /401.html
你还记得在发送标头后 die() 吗? 404 标头不会自动停止处理,因此如果有进一步的处理发生,它可能看起来没有做任何事情。
重定向到您的 404 页面并不好,但您可以毫无问题地包含其中的内容。 这样,您的页面就可以从正确的 URL 正确发送 404 状态,但它也包含您的“您在寻找什么?” 人类读者的页面。
尝试放置
ErrorDocument 404 /(root directory)/(error file)
在.htaccess
文件中。
对任何错误执行此操作,但将 404 替换为您的错误。
在 Drupal 或 Wordpress CMS(以及其他可能的)中,如果您试图使某些自定义 php 代码看起来不存在(除非满足某些条件),通过让 CMS 的 404 处理程序接管以下工作,效果很好:
<?php
if(condition){
do stuff;
} else {
include('index.php');
}
?>
试试这个。
$wp_query->set_404();
status_header(404);
get_template_part('404');
在该行之后立即尝试使用exit
或die()
关闭响应
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
exit;
或者
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
die();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.