views:

15

answers:

1

I currently have the following code:

RewriteCond %{REQUEST_URI} !assets/
RewriteCond %{REQUEST_URI} !uploads/
RewriteRule ^([a-z|0-9_&;=-]+)/([a-z|0-9_&;=-]+) index.php?method=$1&value=$2 [NC,L]

This works perfectly to redirect 'page/home' to 'index.php?method=page&value=home. However at some points I need to add an extra variable or two to the query string such as 'admin/useraccounts/mod/2'. When I simply tack on bits to the end of the rewrite rule it works if all the variables are 'page/home/rand/rand' or 'admin/useraccounts/mod/2', but if anything is missing such as 'page/home' I get a 404.

What am I doing wrong?

Many thanks.

A: 

This should work:

RewriteCond %{REQUEST_URI} !assets/
RewriteCond %{REQUEST_URI} !uploads/
RewriteRule ^([a-z|0-9_&;=-]+)/([a-z|0-9_&;=-]+)(?:/([a-z|0-9_&;=-]+))?(?:/([a-z|0-9_&;=-]+))? index.php?method=$1&value=$2&opt1=$3&opt2=$4 [NC,L]

(?: ) is non capturing group and ? after it makes it optional.

I'm not sure if non capturing groups work in mod_rewrite, if not use normal groups, just take care to use right number after $ while extracting values. Like here:

RewriteCond %{REQUEST_URI} !assets/
RewriteCond %{REQUEST_URI} !uploads/
RewriteRule ^([a-z|0-9_&;=-]+)/([a-z|0-9_&;=-]+)(/([a-z|0-9_&;=-]+))?(/([a-z|0-9_&;=-]+))? index.php?method=$1&value=$2&opt1=$4&opt2=$6 [NC,L]

Groups are numbered as if you were to number their opening braces left to right starting from 1.

Kamil Szot
Thanks Kamil, works perfectly!I understand the ? to make it optional, but can you just explain what you mean by 'non capturing groups' please?
James Doc