htaccess 页面根据参数条件重定向
htaccess page redirect on parameters condition
如何根据 URL 中的参数数量在 .htaccess
中应用不同的 RewriteRule?例如,
1) 如果 URL 有 1 个参数,那么它应该转到 products.php
www.domain.com/mobile
RewriteRule ^([0-9a-zA-Z_-]+) products.php?parent= [NC,L]
2) 如果它有 2 个参数那么它应该转到 category.php
www.domain.com/mobile/apple
RewriteRule ^([0-9a-zA-Z_-]+)/([0-9a-zA-Z_-]+) category.php?parent=&child= [NC,L]
3) 如果它有 3 个参数那么它应该去 list.php
www.domain.com/mobile/apple/iphone6
RewriteRule ^([0-9a-zA-Z_-]+)/([0-9a-zA-Z_-]+)/([0-9a-zA-Z_-]+) list.php?parent=&child=&subchild= [NC,L]
我是 .htaccess
的新手,但如您所见,我已经学会了编写 RewriteRule 但无法理解如何将上述所有规则放入一个 .htaccess 文件,因为如果我这样写
RewriteEngine On
RewriteRule ^([0-9a-zA-Z_-]+) products.php?parent= [NC,L]
RewriteRule ^([0-9a-zA-Z_-]+)/([0-9a-zA-Z_-]+) category.php?parent=&child= [NC,L]
RewriteRule ^([0-9a-zA-Z_-]+)/([0-9a-zA-Z_-]+)/([0-9a-zA-Z_-]+) list.php?parent=&child=&subchild= [NC,L]
它会变得混乱和偏离轨道,但如何根据参数的数量应用上述规则?我希望我的问题够清楚了。
我的意思是如果这是一个编程问题而不是像这样的问题
if($countParameters = 1)
{
//Rule 1
}
else if($countParameters = 2)
{
//Rule 2
}
else if($countParameters = 3)
{
//Rule 3
}
但是它 .htaccess
我不明白如何根据参数的数量应用我的规则。
是的,请务必在您的正则表达式中使用锚点 $
,以确保它不会超出预期的匹配范围。
RewriteEngine On
RewriteRule ^([\w-]+)/?$ products.php?parent= [QSA,L]
RewriteRule ^([\w-]+)/([\w-]+)/?$ category.php?parent=&child= [QSA,L]
RewriteRule ^([\w-]+)/([\w-]+)/([\w-]+)/?$ list.php?parent=&child=&subchild= [QSA,L]
/?$
允许在您的 URL 末尾使用可选的尾部斜杠
- 注意我使用了
\w
而不是 [a-zA-Z0-9_]
如何根据 URL 中的参数数量在 .htaccess
中应用不同的 RewriteRule?例如,
1) 如果 URL 有 1 个参数,那么它应该转到 products.php
www.domain.com/mobile
RewriteRule ^([0-9a-zA-Z_-]+) products.php?parent= [NC,L]
2) 如果它有 2 个参数那么它应该转到 category.php
www.domain.com/mobile/apple
RewriteRule ^([0-9a-zA-Z_-]+)/([0-9a-zA-Z_-]+) category.php?parent=&child= [NC,L]
3) 如果它有 3 个参数那么它应该去 list.php
www.domain.com/mobile/apple/iphone6
RewriteRule ^([0-9a-zA-Z_-]+)/([0-9a-zA-Z_-]+)/([0-9a-zA-Z_-]+) list.php?parent=&child=&subchild= [NC,L]
我是 .htaccess
的新手,但如您所见,我已经学会了编写 RewriteRule 但无法理解如何将上述所有规则放入一个 .htaccess 文件,因为如果我这样写
RewriteEngine On
RewriteRule ^([0-9a-zA-Z_-]+) products.php?parent= [NC,L]
RewriteRule ^([0-9a-zA-Z_-]+)/([0-9a-zA-Z_-]+) category.php?parent=&child= [NC,L]
RewriteRule ^([0-9a-zA-Z_-]+)/([0-9a-zA-Z_-]+)/([0-9a-zA-Z_-]+) list.php?parent=&child=&subchild= [NC,L]
它会变得混乱和偏离轨道,但如何根据参数的数量应用上述规则?我希望我的问题够清楚了。
我的意思是如果这是一个编程问题而不是像这样的问题
if($countParameters = 1)
{
//Rule 1
}
else if($countParameters = 2)
{
//Rule 2
}
else if($countParameters = 3)
{
//Rule 3
}
但是它 .htaccess
我不明白如何根据参数的数量应用我的规则。
是的,请务必在您的正则表达式中使用锚点 $
,以确保它不会超出预期的匹配范围。
RewriteEngine On
RewriteRule ^([\w-]+)/?$ products.php?parent= [QSA,L]
RewriteRule ^([\w-]+)/([\w-]+)/?$ category.php?parent=&child= [QSA,L]
RewriteRule ^([\w-]+)/([\w-]+)/([\w-]+)/?$ list.php?parent=&child=&subchild= [QSA,L]
/?$
允许在您的 URL 末尾使用可选的尾部斜杠- 注意我使用了
\w
而不是[a-zA-Z0-9_]