2010-09-08 48 views
0

我想在.htaccess中使用RewriteRules來實現特定的URL重寫,但不能得到它的權利,可以somoene幫助?幫助與動態RewriteRule在.htaccess

我試圖重寫路徑(第一和最後一個/之間的所有內容)成一個查詢字符串,併到另一個

如文件名:

http://domain.com/users/admins/testuser.html 
rewrites to 
http://domain.com/index.php?path=users/admins&file=testuser 

and 

http://domain.com/home.html 
rewrites to 
http://domain.com/index.php?path=&file=home 

and 

http://domain.com/settings/account.html 
rewrites to 
http://domain.com/index.php?path=settings&file=account 

編輯: 非常感謝對前兩位回答者來說,他們都是很好的答案,但我無法確定使用哪一個! 從php本身解析路徑有沒有什麼好處,反之亦然?

回答

2

試試這個規則:

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^((.+)/)?([^/]+)\.[^/.]+$ index.php?path=$2&file=$3 

但它可能是更容易使用爲PHP’s parse_urlpathinfo

$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); 
$pathinfo = pathinfo(substr($_SERVER['REQUEST_URI_PATH'], 1)); 
var_dump($pathinfo); 

現在你只需要這條規則重寫請求指數.php

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule !^index.php$ index.php 
+0

解析php中的路徑有什麼好處嗎? – Greg 2010-09-08 10:05:43

+0

@Greg:使用PHP比mod_rewrite更靈活,因爲PHP比mod_rewrite更強大。 – Gumbo 2010-09-08 10:11:22

+0

我已經想過了,我更喜歡這種方式,因爲它可以用來定義在您的項目中使用的命名常量,並且單個腳本可以處理所有請求(而不僅僅是.html)。謝謝,你有一個很大的綠色壁蝨! – Greg 2010-09-08 10:14:32

1

試試這個:

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^((\w+/)*)(\w+)\.html$ index.php?path=$1&file=$3 
+0

有沒有這樣做的好處,而不是解析php中的路徑? – Greg 2010-09-08 10:05:04