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 Answer 1

3

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]
Sign up to request clarification or add additional context in comments.

2 Comments

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: Ah yes, forgot to explode.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.