如何在PHP中显示Apache的默认404页面
我有一个 Web 应用程序需要处理 URI 以查找数据库中是否存在页面。我可以使用 .htaccess 将 URI 定向到应用程序:
Options +FollowSymlinks
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.*)$ index.php?p=$1 [NC]
我的问题是,如果页面不存在,我不想使用用 PHP 编写的自定义 404 处理程序,我想显示默认的 Apache 404 页面。当 PHP 确定页面不存在时,有没有办法让 PHP 将执行交还给 Apache?
I have a webapp that needs to process the URI to find if a page exists in a database. I have no problem directing the URI to the app with .htaccess:
Options +FollowSymlinks
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.*)$ index.php?p=$1 [NC]
My problem is that if the page does not exist, I do not want to use a custom 404 handler written in PHP, I would like do show the default Apache 404 page. Is there any way to get PHP to hand execution back to Apache when it has determined that the page does not exist?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不认为您可以将其“交回”给 Apache,但您可以发送适当的 HTTP 标头,然后显式包含您的 404 文件,如下所示:
更新
PHP 5.4 引入了 http_response_code 函数这使得它更容易记住。
I don't think you can "hand it back" to Apache, but you can send the appropriate HTTP header and then explicitly include your 404 file like this:
Update
PHP 5.4 introduced the http_response_code function which makes this a little easier to remember.
对于上述情况,我知道的唯一可能的方法是在您的
index.php
中包含这种类型的 php 代码:然后稍微修改您的 .htaccess,如下所示:
这样 Apache 将显示默认 404这种特殊情况的页面,因为从 php 代码添加了额外的查询参数
?notFound=1
,并且在 .htaccess 页面中对相同的内容进行了否定检查,下次不会将其转发到 index.php。PS:像
/foo
这样的URI,如果在数据库中找不到,在浏览器中将变成/foo?notFound=1
。The only possible way I am aware of for the above scenario is to have this type of php code in your
index.php
:And then slightly modify your .htaccess like this:
That way Apache will show default 404 page for this special case because of extra query parameter
?notFound=1
added from php code and with the negative check for the same in .htaccess page it will not be forwarded to index.php next time.PS: A URI like
/foo
, if not found in database will become/foo?notFound=1
in the browser.调用这个函数:
Call this function: