問題描述
重定向太多。設置 htaccess 以重定向 (too many redirects. setting up htaccess to redirect)
我把一個舊網站移到了一個新的cms,有些內容的鏈接在新系統上找不到。
例如在舊系統中有一個鏈接叫做https://example.com/newsletter/1234/123 在新的我最後不需要這些 id . 因此,我想直接將用戶重定向到 https://example.com/newsletter/。 p>
我在我的 htaccess 文件中寫了以下內容:
RewriteRule ^(.*newsletter)(.*) $1 [L,R=301]
不幸的是,這給了我一個“太男人的重定向”。錯誤。誰能指出我犯的錯誤?
我計劃使用正則表達式來捕獲包含名稱“newsletter”的所有鏈接。並刪除 URL 的其餘部分以重定向用戶。感謝任何幫助。
參考解法
方法 1:
Using (.*newsletter)(.*)
causes the rewrite to match /newsletter
alone because .*
matches zero or more characters. This sends mod_rewrite into a loop.
Instead, you can use .+
which matches one or more characters, and to that I would prepend /?
to optionally match a trailing slash. There is no need to capture it in ()
because you do not reuse it as $2
.
RewriteRule ^(.*newsletter)/?.+ $1 [L,R=301]
Your example began with .*
. If you actually need that, leave it in. But if you are really just trying to match /newsletter/123/1234
and not /someother/newsletter/123/1234
, simplify it with:
RewriteRule ^newsletter/?.+ /newsletter [L,R=301]
When you test this, use a private/incognito browsing window or a fresh browser. Browsers aggressively cache 301 redirects and it can make it very hard to debug rewrite rules if you are fighting against the cache.
(by K Nugal、Michael Berkowski)