views:

124

answers:

1

How to rewrite a url like:

http://domain.com/class/method/parameter1/parameter2/.../parameterN

to

http://domain.com/index.php?c=class&m=method&p1=parameter1&...&pN=parameterN

The main idea is to create the possibility of using unlimited number of query parameters.

Thanks.

+1  A: 

It is possible to do that with Apache’s mod_rewrite module like this:

RewriteRule ^/([^/]+/[^/]+)/([^/]+)(/.+)?$ /$1$3?p[]=$2 [N,QSA]
RewriteRule ^/([^/]+)/([^/]+)$ /index.php?c=$1&m=$2 [L,QSA]

But it would definitely be easier to do that with PHP:

$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', trim($_SERVER['REQUEST_URI_PATH'], '/'));
if (count($segments) >= 2) {
    $_GET['class'] = array_shift($segments);
    $_GET['m'] = array_shift($segments);
    $_GET['p'] = $segments;
} else {
    // error
}

Then you just need one single rule to rewrite the requests:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !^index\.php$ index.php [L]
Gumbo
With the addition of: $segments = explode('/', $segments);and some iteration for the remaining query parameters after:$_GET['p'] = array_shift($segments);the simple method you proposed worked like a charm.Thanks.
vbklv
@vbklv: Ah yes, forgot to `explode`.
Gumbo