我已將 wordpress 安裝從子檔案夾移至域根目錄。我已經通過 .htaccess 成功重定向了該子檔案夾,但我完全無法向其中添加查詢字串,因此我知道客戶端何時來自舊鏈接,同時保留請求具有的任何先前查詢字串。
我在 wordpress 指令之后的 .htaccess 檔案中的(唯一)代碼是:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^nbek.org/blog$ [OR]
RewriteCond %{HTTP_HOST} ^nbek.org/blog/$
RewriteRule (.*)$ https://nbek.org/$1?sublog=nox [R=301,QSA,L]
</IfModule>
我也試過:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^nbek.org/blog$ [OR]
RewriteCond %{HTTP_HOST} ^nbek.org/blog/$
RewriteRule ^(.*)$ $1?sublog=nox [QSA]
RewriteRule (.*)$ https://nbek.org/$1 [R=301,L]
</IfModule>
完全沒有成功。我究竟做錯了什么?
uj5u.com熱心網友回復:
我在wordpress 指令之后的 .htaccess 檔案中的(唯一)代碼是:
<IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTP_HOST} ^example.com/blog$ [OR] RewriteCond %{HTTP_HOST} ^example.com/blog/$ RewriteRule (.*)$ https://example.com/$1?sublog=nox [R=301,QSA,L] </IfModule>
正如評論中所述,這些指令不能做任何事情,因為條件(RewriteCond指令)永遠不會匹配。HTTP_HOST服務器變數包含 HTTP 請求標頭的值-Host這不包含 URL 路徑。所以,example.com/blog永遠無法匹配。
您還將這些指令放在錯誤的位置,它們需要放在WordPress 代碼塊之前,而不是“之后”。通過將此規則放在“Wordpress 指令之后”,除非/blog仍然作為物理目錄存在,否則(再次)這些指令將永遠不會真正做任何事情,因為它們甚至永遠不會被處理(WordPress 代碼塊捕獲請求并將其重寫到前面-控制器,此時處理有效停止)。如果/blog仍然作為物理目錄存在,則前面的 WordPress 代碼塊應忽略請求,允許處理此規則。
我可以向您保證重定向完成得很好。有點慢但很好。
這可能表明重定向實際上是由 WordPress 本身執行的,而不是.htaccess. 但是,這個“應該”在重定向回應的 HTTP 回應標頭中指明。
將所有請求從/blog子目錄重定向到根目錄并包含一個額外的 URL 引數只是一種方法。
例如,在WordPress 代碼塊之前:
# Redirect "/blog/<anything>" to "/<anything>?sublog=nox"
RewriteRule ^blog(?:$|/(.*)) /$1?sublog=nox [QSA,R=301,L]
# BEGIN WordPress
:
或者,通過在重定向中包含方案和主機名來確保它始終重定向到 HTTPS 和規范主機名(正如您所做的那樣):
RewriteRule ^blog(?:$|/(.*)) https://example.com/$1?sublog=nox [QSA,R=301,L]
這將重定向/blog到/?sublog=nox和/blog/foo?bar=1到/foo?sublog=nox&bar=1(保留初始查詢字串)。
The RewriteRule directive itself checks the URL-path in the first argument (ie. ^blog(?:$|/(.*))). The additional "complexity" in the regex is that this will match both /blog (no trailing slash) and /blog/<anything> and still preserve the slash prefix in the substitution string without duplication.
The QSA flag appends the original query string (if any) from the initial request onto the end of the substitution string.
Additional notes:
- You do not need any additional conditions (
RewriteConddirectives) before the rule. - You do not need to repeat the
RewriteEngine Ondirective, since this should already occur later in the file, inside the WordPress code block. - You do not need the
<IfModule>wrapper around these directives. These directives are not optional.
Reference
The official Apache docs should be your go to reference for this (although the docs are rather concise and somewhat lacking examples in places):
- Apache mod-rewrite Contents
- Apache mod_rewrite Introduction
- Apache mod_rewrite Reference
RewriteRuleDirectiveRewriteCondDirective
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/449441.html
