2010-09-08 40 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