2015-05-19 62 views
1

我知道類似的問題已經被問到,但我找不到任何有關我的具體「問題」的信息。 我想要做的是在一個非常動態的方式,這意味着「超級用戶」應該能夠在一個管理界面來定義新的路線如下:如果用戶輸入http://www.example.com/nice-url/Joomla-like url rewrite

他應該得到

重定向到http://www.example.com/category.php?id=123而不更改網址。

現在有幾種方法可以實現這一點。無論是我使用的.htaccess這樣的:

RewriteEngine on 
RewriteRule ^nice-url category.php?id=123 [L] 

這工作,但不是很活躍。我需要讓PHP腳本在底部添加新規則,這不是我想要做的事情。

或者這樣:

的.htaccess

FallbackResource /process.php 

process.php

$path = ltrim($_SERVER['REQUEST_URI'], '/'); 
$elements = explode('/', $path);    

if(count($elements) == 0) {     
    header("Location: http://www.example.com"); 
    exit; 
} 

$sql = sprintf("SELECT Target FROM urlrewrites WHERE Source = '%s' LIMIT 1", array_shift($elements)); 
$result = execQuery($sql); 
$row = mysqli_fetch_array($result, MYSQLI_ASSOC); 
$target = $row['Target']; 

header("Location: ".$target); 
exit; 

這也適用,但遺憾的是在地址欄中的URL得到改變。兩者中間有沒有辦法?具有PHP的靈活性和RewriteEngine的「沉默」?偉大的CMS如joomla如何做到這一點?他們是否爲您創建的每個新頁面生成一個htaccess文件? 謝謝!

回答

0

你可以有這樣的代碼在根目錄的.htaccess:

RewriteEngine on 

# If the request is not for a valid directory 
RewriteCond %{REQUEST_FILENAME} !-d 
# If the request is not for a valid file 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^(.*)$ category.php?uri=$1 [L,QSA] 

PS:注意這將路線/nice-url/category.php?uri=nice-url。然後在category.php內,您可以進入數據庫並將$_GET['uri']轉換爲id

0

如果您使用正則表達式,它會更具動態性。這就是它在Joomla等CMS系統中的工作原理。好主意是在Joomla上安裝'nice'網址並查看.htacces文件以瞭解它是如何工作的。 你可以從這裏開始: http://www.elated.com/articles/mod-rewrite-tutorial-for-absolute-beginners/

+0

那麼我知道正則表達式。我的主要問題是:他們如何處理額外的頁面,由用戶添加?我不相信他們在添加新頁面時重寫整個.htaccess文件。問題還在於我不知道具體的路線。 – puelo

+0

在Joomla中,它使用路由機制來實現,其概念在此處描述:https://docs.joomla.org/Supporting_SEF_URLs_in_your_component ,總體思路如下: https://docs.joomla.org/Routing_implementation_details –