htaccess页面重定向参数条件

How can I apply different RewriteRule in .htaccess depending on number of parameters in URL? For example,

1) If the URL has 1 parameter than it should go to products.php

 www.domain.com/mobile
 RewriteRule ^([0-9a-zA-Z_-]+) products.php?parent=$1 [NC,L]

2) If it has 2 parameters then it should go to category.php

 www.domain.com/mobile/apple
 RewriteRule ^([0-9a-zA-Z_-]+)/([0-9a-zA-Z_-]+) category.php?parent=$1&child=$2 [NC,L]

3) If it has 3 parameters then it should go to list.php

 www.domain.com/mobile/apple/iphone6
 RewriteRule ^([0-9a-zA-Z_-]+)/([0-9a-zA-Z_-]+)/([0-9a-zA-Z_-]+) list.php?parent=$1&child=$2&subchild=$3 [NC,L]

I am a newbie in .htaccess but as you can see I have learnt to write RewriteRule but cannot understand that how can I put all of my above rules in one single .htaccess file because if I put it like this

RewriteEngine On
RewriteRule ^([0-9a-zA-Z_-]+) products.php?parent=$1 [NC,L]
RewriteRule ^([0-9a-zA-Z_-]+)/([0-9a-zA-Z_-]+) category.php?parent=$1&child=$2 [NC,L]
RewriteRule ^([0-9a-zA-Z_-]+)/([0-9a-zA-Z_-]+)/([0-9a-zA-Z_-]+) list.php?parent=$1&child=$2&subchild=$3 [NC,L]

it gets confused and off-course it should be but how can apply these above rules depending on number of parameters? I hope I made my question clear enough.

I meant to say that if it was a programming question than something like this

if($countParameters = 1)
{
   //Rule 1
}
else if($countParameters = 2)
{
   //Rule 2
}
else if($countParameters = 3)
{
   //Rule 3
}

but its .htaccess and I cannot understand how can I apply my rules depending on number of parameters.

Yes sure, make sure to use anchor $ in your regex to make sure it doesn't match more than intended.

RewriteEngine On
RewriteRule ^([\w-]+)/?$ products.php?parent=$1 [QSA,L]
RewriteRule ^([\w-]+)/([\w-]+)/?$ category.php?parent=$1&child=$2 [QSA,L]
RewriteRule ^([\w-]+)/([\w-]+)/([\w-]+)/?$ list.php?parent=$1&child=$2&subchild=$3 [QSA,L]
  • /?$ allows an optional trailing slash at the end of your URLs
  • Note I have used \w instead of [a-zA-Z0-9_]