duanshan5259 2015-02-11 15:17
浏览 91
已采纳

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.

  • 写回答

1条回答 默认 最新

  • dtotuki47568 2015-02-11 15:19
    关注

    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_]
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 angular开发过程中,想要读取模型文件,即图1的335行,会报404错误(如图2)。但我的springboot里配置了静态资源文件,如图3。且在该地址下我有模型文件如图4,请问该问题该如何解决呢?
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 vite打包后,页面出现h.createElement is not a function,但本地运行正常
  • ¥15 Java,消息推送配置