正则表达式匹配带斜杠和不带斜杠的 url

Regex to match url with and without slash

提问人:Guy 提问时间:7/9/2023 最后编辑:anubhavaGuy 更新时间:7/10/2023 访问量:57

问:

我们在 .htaccess 中有这个正则表达式

RewriteRule ^([^\.]+)$ $1.html

它将 url 匹配如下: 到一个名为https://example.com/liblib.html

我们还需要它匹配: 到同一个文件https://example.com/lib/

谢谢。

试:

RewriteRule ^([^\.]+)?/$ $1.html
RewriteRule ^([^\.]+[^/]*)$ $1.html
正则表达式 URL mod-rewrite

评论

0赞 The fourth bird 7/9/2023
喜欢 regex101.com/r/ESakrS/1^([^\./]+)/?$
3赞 anubhava 7/9/2023
尝试RewriteRule ^([^./]+)/?$ $1.html [L]
2赞 The fourth bird 7/9/2023
@anubhava 请发布您的解决方案。
0赞 Guy 7/9/2023
这些都行不通。如果这很重要,我可能应该添加一下。

答:

-1赞 jean claude N'guetta 7/9/2023 #1

你好试试这个正则表达式(\w+)\/?$

评论

0赞 Guy 7/9/2023
您好,谢谢。但不好。而且每次我尝试/?在 () 之后,non / url 也不匹配。
0赞 Ted Lyngmo 7/10/2023 #2

您可以将其重写为两个单独的规则以保持简单:

RewriteRule (?!.*\.html$)^(.+)\/$ $1.html [last]
RewriteRule (?!.*\.html$)^(.+)$ $1.html [last]

它将首先尝试匹配以结尾的 URL 上的 URL,如果失败,它将继续执行下一条规则。否定的展望是,不重写已经以 . 结尾的 URL/(?!.*\.html$).html

该标志使其停止处理更多规则,以防出现匹配项。[last]

如果您希望将两者合并到一个规则中:

RewriteRule (?!.*\.html$)^(.+?)\/?$ $1.html [last]