[英]How to efficiently match a .htaccess RewriteRule for a complete word only if it's the last part of the URL
我不確定如何表達這個請求,所以請耐心等待我舉例說明。 我會盡量說清楚。
如果 URL 以兩個詞之一結尾,我希望重定向它,比方說foo
或bar
。 它必須只匹配一個完整的詞,所以food
或new-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,但我對如何 go 感到困惑。)
謝謝
這可能是您正在尋找的:
RewriteEngine on
RewriteRule (?:^|/)(foo|bar)/?$ https://example.com/$1/ [L,R=301]
(?:^|/)
是一個“非捕獲組”,因此$1
仍然指的是(foo|bar)
捕獲的內容,而整個表達式與請求的 URL 僅匹配這些詞或將這些詞作為最終文件夾路徑序列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.