views:

13

answers:

2

Hi, I would like to use RewriteRules in .htaccess to achieve particular url rewriting, but can't get it right, can somoene help?

I'm trying to rewrite the path (everything between the first and last /) into one query string, and the filename into another

e.g:

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

EDIT: Many thanks to the first two answerers, they are both good answers however I can't figure which one to use! Is there any benefit to parsing the path from php itself, or vice-versa?

+1  A: 

Try this rule:

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

But it may be easier to use PHP’s parse_url and pathinfo for that:

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

Now you just need this rule to rewrite the request to the index.php:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !^index.php$ index.php
Gumbo
is there any benefit to parsing the path in php?
Greg
@Greg: Using PHP is more flexible than mod_rewrite as PHP is more powerful than mod_rewrite.
Gumbo
@Gumbo: I've thought about it and I prefer this way because it can be used to define named constants for use within your project, and the single script can handle all requests (not just .html). Thanks, you got a big green tick!
Greg
+1  A: 

Try this:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^((\w+/)*)(\w+)\.html$ index.php?path=$1&file=$3
aularon
is there any benefit to doing it like this, rather than parsing the path in php?
Greg