views:

237

answers:

4

What would be the valid .htaccess rules for doing something like this

/mypage/ --> /index.php?page=mypage
/mypage/param1/value1/ -->index.php?page=mypage&params=param1/value1

With an potentially unlimited number of parameters?

Thanks.

+4  A: 

Best is to to pass the entire part after the /mypage/ as an param to the php script and have that decode it:

RewriteRule ^mypage/(.*) index.php?page=mypage&params=$1 [L,NC,QSA]

Also if you want page to be dynamic:

RewriteRule ^([^/\.]+)/(.*) index.php?page=$1&params=$2 [L,NC,QSA]

or

RewriteRule ^([^/\.]+)(/(.*))? index.php?page=$1&params=$3 [L,QSA]

EDIT
Added Cal's suggestion, thanks Cal.

Edit
If I understand your comment correctly: (if not please explain). You can just use a switch statement with a default action which is the same as the index action for the page variable:

switch($_GET['page']){
 case 'mypage':
  doMyPageStuff();
 break;
 case 'foo':
  doFooStuff();
 break;
 case 'index':
 default:
  doIndexStuff();
 break;
}
Pim Jager
The second method is what I need more of but how do I ignore the / after mypage?
Daniel A. White
Cal
In these rewriteRules the / won't be added to the page parameter, what excactly do you mean?
Pim Jager
for my http://mysite.com/ i get index as $1. How can I catch that?
Daniel A. White
You want to get it or you wan't it to default to index? See my updated answer if it does what you want, otherwise please specify.
Pim Jager
typo: deafult = default
benlumley
+1  A: 
RewriteRule ^([^/]+)/(.+)/?$    index.php?page=$1&params=$2

Or very similar - not got a server at hand to check!

benlumley
A: 

I see this already has an accepted answer, but I believe the following will do what you want using only mod_rewrite.

RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^(.*/)([^/]+)/([^/]+) $1?$2=$3&%1 [L]
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^([^/]+)/ $1.php?%1 [L]

It works because mod_rewrite behaves recursively. That is, after every rewrite, the new URL is processed again. Each time through, the two values on the end are turned into query parameters and added to the query string.

This will rewrite the following

/mypage/param1/val1/param2/val2/param3/val3/...     --->
/mypage.php?param1=val1&param2=val2&param3=val3&...

It stops when there is only one parameter remaining. It will take the first "parameter" and call the .php file with that name. There is no limit to the number of param/val pairs.

--
bmb

bmb
+1  A: 

Here’s my proposal:

RewriteRule ^([^/]+)/(([^/]+/[^/]+(/[^/]+/[^/]+)*)/)?$ /index.php?page=$1&params=$3 [L]

This is not very nice but exaclty as you requested. It only allows paths of the form:

/mypage/
/mypage/param1/value1/
/mypage/param1/value1/param2/value2/
/mypage/param1/value1/param2/value2/param3/value3/
/mypage/param1/value1/param2/value2/param3/value3/param4/value4/
…
Gumbo