如果尾部斜杠不存在,我想向特定的URL结构添加尾部斜杠。此URL应为:
/product/product-#/
另一个条件是,如果URL有后续子文件夹,则不应将尾部斜杠添加到URL中。此URL应为:
/product/product-#/subfolder/subpage
因此,下面的示例URL应该以斜杠结尾:
/product/product-1 becomes /product/product-1/
/product/product-2 becomes /product/product-2/
/product/product-3 becomes /product/product-3/
/product/product-4/ remains /product/product-4/
因此,以下示例URL不应以斜杠结尾:
/product/product-1/subfolder/1456 remains /product/product1/subfolder/1456
/product/product-2/subfolder/6789 remains /product/product-2/subfolder/6789
我在这里的尝试不起作用,子文件夹后面的斜杠没有在非捕获组中注册。
/(?!.*(?:subfolder/[0-9]{4})$)[^/]+$
使用所示的示例,请尝试以下regex。
^(/[^/]*/[^/]*)/?$
在进行url重写时,需要在替换部分使用$1/
。
以上regex 的在线演示
解释:添加以上详细解释。
^ ##Matching from starting of value here.
( ##Starting capturing group from here.
/[^/]*/[^/]* ##Matching 1 slash followed by values till next slash comes.
##Followed by slash and match all values till next slash comes
) ##Closing capturing group here.
/?$ ##Matching optional / at the end of value here.