问题描述
如果不存在尾随斜杠,我想向特定 URL 结构添加尾随斜杠。此网址应为:
/product/product-#/
另一个条件是,如果 URL 具有后续子文件夹,则不应将尾部斜杠添加到 URL。此网址应为:
/product/product-#/subfolder/subpage
因此,以下示例网址应以斜杠结尾:
/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/
因此,以下示例网址不应以斜杠结尾:
/product/product-1/subfolder/1456 remains /product/product1/subfolder/1456
/product/product-2/subfolder/6789 remains /product/product-2/subfolder/6789
我的尝试 here 不起作用,子文件夹后面的斜杠未在非捕获组中注册。
\/(?!.*(?:subfolder\/[0-9]{4})$)[^\/]+$
解决方法
对于您显示的示例,请尝试以下正则表达式。
^(\/[^\/]*\/[^\/]*)\/?$
您在进行 url-rewriting 时需要在替换部分使用 $1/
。
说明:为以上添加详细说明。
^ ##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.