[英]rewrite pretty urls with php and htaccess, mapping 404 for subpages
在.htaccess中,我有以下規則來重寫頁面/子頁面。
#Permalinks
RewriteEngine on
<IfModule mod_rewrite.c>
RewriteEngine On
#catch potential subpages first
RewriteRule ^([a-z\-]+)/([a-z\-]+)/?$ index.php?page=$1&subpage=$2 [L]
#
RewriteRule ^([a-z\-]+)$ index.php?page=$1 [L]
</IfModule>
在PHP中我這樣做:
if (!$_GET) {
//
$page = "home";
$page_title = "General Site Title";
include ("template/index.php");
//
} else if ($_GET['page'] == "words") {
//
$page = "words";
$page_title = "Words Page";
include ("template/words.php");
//
} else if ($_GET['page'] == "about") {
//
$page = "about";
$page_title = "About Page";
include ("template/about.php");
//
} else {
//
header("HTTP/1.0 404 Not Found");
//
include ("template/404.php");
//
exit();
//
}
當頁面不存在時顯示404.php效果很好。
但是,如果我不希望頁面/子頁面不存在時也想擁有404.php怎么辦?
例如,我打算擁有/ members頁面。 如果有人去不存在的/ members / user1,我需要檢查數據庫是否存在現有用戶,如果不存在,我應該顯示404.php,但是在這種情況下可以使用這種正確的邏輯嗎?
ps我如何添加重寫/ about /以顯示同一頁面? 當前/ about返回200,但是/ about /返回找不到apache頁面。
首先對規則進行更正,以使兩個規則中的尾部斜杠均可選:
RewriteEngine On
RewriteRule ^([a-z-]+)/([a-z-]+)/?$ index.php?page=$1&subpage=$2 [L,NC,QSA]
RewriteRule ^([a-z-]+)/?$ index.php?page=$1 [L,NC,QSA]
現在關於檢查/members/user1
是的,您可以檢查數據庫是否存在成員記錄,如果找不到,則可以返回404狀態/頁面。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.