在mod_rewrite中匹配字符串或无匹配的正则表达式

时间:2014-01-09 06:51:33

标签: regex mod-rewrite

我正在做一个正则表达式,以便将以下网址与相应的文件匹配

/main/type1/dog/type2/food                index.php?t1=dog&t2=food 
/main/type1/dog/type2/food/               index.php?t1=dog&t2=food 
/main/type1/dog/type2/food/menu/puppy     index.php?t1=dog&t2=food&menu=puppy 
/main/type1/cat/type2/toy/menu/adult      index.php?t1=cat&t2=toy&menu=adult


RewriteRule ^/?main/type1/([a-z]+)/type2/([a-z]+)/?(|(menu)/([a-z]+))$   index.php?t1=$1&t2=$2&$menu=$3 [L] 

但它没有像我期望的那样起作用。专家解决它的任何线索?谢谢!

3 个答案:

答案 0 :(得分:0)

您可以使用以下正则表达式:

^/?main/type1/([a-z]+)/type2/([a-z]+)(/|(/menu/([a-z]+)/?))?$

答案 1 :(得分:0)

尝试:

RewriteRule ^/?main/type1/([a-z]+)/type2/([a-z]+)(?:/(menu)/([a-z]+)|)/?$ index.php?t1=$1&t2=$2&$3=$4 [L] 

这样,如果menu部分不存在,参数将不会传递到index.php脚本中。

答案 2 :(得分:0)

除非你的查询字符串末尾有&=,否则最好有2个单独的规则:

# for URL with 2 query parameters
RewriteRule ^/?main/[^/]+/([^/]+)/[^/]+/([^/]+)/?$ index.php?t1=$1&t2=$1 [NC,L,QSA]

# for URL with 3 query parameters
RewriteRule ^/?main/[^/]+/([^/]+)/[^/]+/([^/]+)/([^/]+)/([^/]+)/?$ index.php?t1=$1&t2=$1&$3=$4 [NC,L,QSA]
相关问题