如何将两条.htaccess RewriteRule规则合并为一条?
合并后的.htaccess RewriteRule方案
可以通过将两条规则的正则分支用|(逻辑或)合并,并利用捕获组拼接确保两种场景下type参数能正确取值,最终合并规则如下:
RewriteRule ^discography\/(?:type(?:\/(?:(?:[^\/]*[.])?(\d+)\/?|[^\/]+\/?)?)|(ep|singles)\/?)$ discography/releases.php?type=$1$2 [L,QSA]
逻辑说明
- 原type规则分支:保留对
discography/type开头路径的匹配逻辑,捕获点后(或无点时)的首个整数存入第一个捕获组$1 - 原ep/singles规则分支:匹配
discography/ep或discography/singles路径,捕获对应的关键词存入第二个捕获组$2 - 参数传递:通过
$1$2拼接两个捕获组的值——匹配type分支时$2为空,最终传递整数;匹配ep/singles分支时$1为空,最终传递关键词,完全兼容原两条规则的参数需求
匹配验证
有效匹配(与原规则一致)
- type分支:
discography/type、discography/type/、discography/type/4、discography/type/albums.4 - ep/singles分支:
discography/ep、discography/ep/、discography/singles、discography/singles/
无效匹配(与原规则一致)
discography/type/4//、discography/type//、discography/type/singles.4//(双斜杠场景不匹配正则)
内容的提问来源于stack exchange,提问作者Marco
相关产品推荐
相关产品推荐

