Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

apache mod_rewrite one rule for any number of possibilities

I'm building a fairly large website and my .htaccess is starting to feel a bit bloated, is there a way of replacing my current system of - one rule for each of the possibile number of vars that could be passed, to one catch all expression that can account for varying numbers of inputs ?

for example I currently have:

RewriteRule ^([a-z]+)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)$ /index.php?mode=$1&id=$2&$3=$4&$5=$6
RewriteRule ^([a-z]+)/([^/]*)/([^/]*)/([^/]*)$ /index.php?mode=$1&id=$2&$3=$4
RewriteRule ^([a-z]+)/([^/]*)$ /index.php?mode=$1&id=$2
RewriteRule ^([a-z]+)$ /index.php?mode=$1

the first backreference is always the mode and (if any more exist) the second is always id, thereafter any further backreferences alternate between the name of the input and its value

http://www.example.com/search
http://www.example.com/search/3039/sort_by/name_asc/page/23

I would love to be able to have one expression to gracefully handle all the inputs.

like image 266
JimmyJ Avatar asked Sep 22 '08 22:09

JimmyJ


1 Answers

Do like Drupal:

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

And then handle all the stuff in your script using php code something like this

$pathmap = ();
if ($_GET["q"]){
    $path = split("/", $_GET["q"]);
    for ($i=0; $i+1<count($path); $i++){
        $pathmap[$path[$i]] = $path[$i+1];
        $i++;
    }
}
like image 129
daniels Avatar answered Sep 18 '22 17:09

daniels