2011-05-10 121 views
14

我有一个web应用程序需要处理URI以查找数据库中是否存在页面。我没有问题,指导URI到应用程序与的.htaccess:如何在PHP中显示Apache的默认404页面

Options +FollowSymlinks 
RewriteEngine on 
RewriteCond %{SCRIPT_FILENAME} !-f 
RewriteRule ^(.*)$ index.php?p=$1 [NC] 

我的问题是,如果页面不存在,我不想用PHP编写的定制404处理器,我想这样做显示默认的Apache 404页面。有什么办法可以让PHP在确定页面不存在时将执行回执给Apache?

+0

不是。你可以通过'header('Location:...')'做一个简单的重定向到404页面,但是这会显示为'200 OK'请求,这被认为是不好的做法。 – 2011-05-10 16:17:30

+1

这可能会帮助你:http://stackoverflow.com/questions/4232385/php-or-htaccess-make-dynamic-url-page-to-go-404-when-item-is-missing-in-db – 2011-05-10 16:19:38

+0

我认为这仍然没有简单的选择,http://stackoverflow.com/q/4856425/345031 – mario 2011-05-10 16:42:47

回答

5

唯一可能的途径我知道对于上述方案是有这种类型的PHP代码在你index.php

<?php 
if (pageNotInDatabase) { 
    header('Location: ' . $_SERVER["REQUEST_URI"] . '?notFound=1'); 
    exit; 
} 

然后稍微修改你的.htaccess这样的:

Options +FollowSymlinks -MultiViews 
RewriteEngine on 
RewriteCond %{SCRIPT_FILENAME} !-f 
RewriteCond %{QUERY_STRING} !notFound=1 [NC] 
RewriteRule ^(.*)$ index.php?p=$1 [NC,L,QSA] 

这样Apache会为这个特例显示默认的404页面,因为额外的查询参数?notFound=1从php代码中加入并带有负值检查对于.htaccess页面中的相同内容,下次不会转发到index.php。

PS:/foo这样的URI,如果在数据库中没有找到,将在浏览器中变成/foo?notFound=1

+0

如果您从404处理程序调用此函数,则会循环。 – Mel 2011-05-10 17:07:11

+0

'header('Location:/ non-existent-page-url');'不应该来自您的自定义404处理程序。看到我的回答,我写了上面的index.php。事实上,如果你想展示Apache的404处理程序,你不应该有一个自定义的404处理程序。我建议首先在你的apache配置或.htaccess中注释'ErrorDocument 404'。 – anubhava 2011-05-10 17:15:41

+0

啊我的坏。误读原始问题。 – Mel 2011-05-10 17:19:32

4

调用此函数:

http_send_status(404); 
+9

这需要pecl_http包,他可能无法安装 – andrewtweber 2011-05-10 16:39:48

+2

良好的观察。 – 2011-05-10 16:40:37

+2

良好的观察 – 2011-05-10 17:05:51

14

我不认为你可以“手回”到Apache,但你可以发送相应的HTTP标头,然后明确包括您的404文件是这样的:

if (! $exists) { 
    header("HTTP/1.0 404 Not Found"); 
    include_once("404.php"); 
    exit; 
} 

更新

PHP 5.4引入了http_response_code功能,这使得这一点更容易remem BER。

if (! $exists) { 
    http_response_code(404); 
    include_once("404.php"); 
    exit; 
}