對我的站點執行404錯誤處理有點困難。通常這不是問題,但在這種情況下,設置是不同的。使用mod_rewrite模式匹配errorDocument規則
我不得不在我的.htaccess文件中使用模式匹配進行URL重寫,即RewriteRule ^([^/]+)\/$
和RewriteRule ^products\/([^/]+)\/([^/]+)\/$
這是由於網站具有受其他用戶控制的CMS,他們可以添加新頁面I.e. www.yourdomain.com/pagename「pagename」是任何新頁面。
任何輸入的URL都可以說「/ about」匹配RewriteRule ^([^/]+)\/$
然後在數據庫中檢查以找到匹配項,如果找到匹配項,則用戶重定向到正確的頁面,如果不匹配,則可以重定向用戶訪問特定頁面或設置http狀態碼。
唯一的問題是我想保留不正確的URL,並且PHP重定向會覆蓋那個。
代碼:
ErrorDocument 403 /errors.php?error=403
ErrorDocument 404 /errors.php?error=404
ErrorDocument 500 /errors.php?error=500
ErrorDocument 503 /errors.php?error=503
RewriteEngine On
RewriteRule ^([^/]+)\/$ ?cat=generic&page=$1 [L]
RewriteRule ^products\/([^/]+)\/([^/]+)\/$ ?cat=product&page=$2 [L]
現在我敢肯定這個問題是由於其重寫規則我在的地方,所以我想我期待的是仍然讓我重寫替代抓住任何新創建的頁面url,但也允許成功的錯誤文檔處理。
如果我遺漏了任何重要的代碼/信息,請讓我知道,我將使用它編輯帖子。
非常感謝您的任何建議/幫助。
編輯::
PHP腳本處理該頁面的內容。
function page_handler() {
if(!isset($_GET['cat'])):
$_GET['cat'] = 'generic';
$_GET['page'] = 'home';
endif;
// Connect to the database
$link = db_connect_cms();
// Grab the id of the page
$qry = mysqli_query($link,"
SELECT hash,slug
FROM cms_web_pages
WHERE slug='".$_GET['page']."'
AND published=1")
or die(mysqli_error($link)
);
$row = mysqli_fetch_object($qry);
// If there is a match in the db
if(mysqli_num_rows($qry) > 0):
$id_hash = $row->hash;
else:
$_GET["error"] = "404";
require_once($_SERVER["DOCUMENT_ROOT"] . "/errors.php");
endif;
return array($id_hash);
}
更好。謝謝你的代碼,它確實顯示了正確的內容,但是使用'include'函數只是增加了已存在頁面中的文件內容。基本上有2頁內1.任何想法? – zealisreal
是的,的確,'include'會在你的頁面內容後顯示來自'errors.php'的內容(即它不會取代你頁面的內容)。 – anubhava
但是,您應該在PHP腳本開始時進行數據庫查找,然後根據查詢結果決定調用上面的include snippet和'exit;'從其餘的PHP代碼中解救出來。 – anubhava