Reputation: 21899
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?
Upvotes: 0
Views: 810
Reputation: 655189
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
Upvotes: 2
Reputation: 11110
Try this:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^((\w+/)*)(\w+)\.html$ index.php?path=$1&file=$3
Upvotes: 1