如何高效地匹配.htaccess RewriteRule,使其仅在URL的最后一部分才匹配完整的单词

ztigrdn8  于 2023-01-26  发布在  其他
关注(0)|答案(1)|浏览(126)

我不知道该如何表达这个请求,所以请耐心听我举个例子解释,我会尽量把它说清楚。
如果URL以两个单词中的一个结尾,例如foobar,我希望重定向该URL。它必须仅作为完整单词匹配,因此foodnew-foo不应匹配。URL可能以斜杠结尾,因此/foo/foo/都有效。
此外,单词本身可能位于URL的开头或较长路径的末尾。
因此,以下任何一项都应匹配,*(带或不带尾部斜杠 *):

https://example.com/foo
https://example.com/new/foo
https://example.com/bar
https://example.com/some/other/bar

但是,以下任何一项都不应匹配(带或不带尾部斜杠):

https://example.com/foo-new
https://example.com/old-bar
https://example.com/bar/thud
https://example.com/plugh/foo/xyzzy

澄清:如果单词重复也没关系,例如,以下内容仍然应该重定向,因为foo位于URL的末尾:

https://example.com/foo/new/foo

我所能想到的最好的方法是使用两个重定向,第一个检查单词本身,第二个检查单词是否是路径的最后一部分:

RewriteRule ^(foo|bar)/?$ https://redirect.com/$1/ [last,redirect=permanent]
RewriteRule /(foo|bar)/?$ https://redirect.com/$1/ [last,redirect=permanent]

最终,会有几个词,而不仅仅是两个...

RewriteRule ^(foo|bar|baz|qux|quux|corge|grault|garply)/?$ https://redirect.com/$1/ [last,redirect=permanent]
RewriteRule /(foo|bar|baz|qux|quux|corge|grault|garply)/?$ https://redirect.com/$1/ [last,redirect=permanent]

...所以使用两个RewriteRule语句看起来容易出错,而且可能效率低下。有没有办法将两个RewriteRule语句组合成一个?或者,也许,您有更好的主意?(我玩弄了FilesMatch,但我不知道如何去做。)
谢谢

lztngnrs

lztngnrs1#

这可能就是你要找的:

RewriteEngine on
RewriteRule (?:^|/)(foo|bar)/?$ https://example.com/$1/ [L,R=301]

(?:^|/)是“非捕获组”,因此$1仍然指的是(foo|bar)捕获的内容,而整个表达式仅利用这些词或者利用这些词作为路径序列中的最终文件夹来匹配所请求的URL。

相关问题