2011-05-10 118 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; 
}