![](/img/trans.png)
[英]AWS & PHP: https website redirects to http when there is no slash at the end
[英]Custom wordpress HTTP redirects to HTTPS breaks website
我在我的.htaccess
文件中添加了額外的規則。
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule !^/articles/(.*)$ https://%{HTTP_HOST}/index.php?name=$1 [L,R=301]
RewriteRule ^(articles/)(.*)$ https://%{HTTP_HOST}/index.php?name=$2 [L,R=301]
</IfModule>
我有兩個似乎有效的條件:
http://example.com/this-is-old-url/
符合第一條重寫規則
http://example.com/articles/this-is-old-url/
符合第二條規則
但問題是,添加這些規則后,我的網站開始到處進行重定向。 例如,我無法訪問我的域https://example.com
,它更改為https://example.com/index.php?name=
。 我所有的網站鏈接都斷了。
我究竟做錯了什么?
RewriteCond %{HTTPS} off RewriteRule !^/articles/(.*)$ https://%{HTTP_HOST}/index.php?name=$1 [L,R=301] RewriteRule ^(articles/)(.*)$ https://%{HTTP_HOST}/index.php?name=$2 [L,R=301]
第一條規則匹配所有內容,因為在.htaccess
上下文中與RewriteRule
模式匹配的 URL-path 從不以斜杠開頭(您似乎已經在第二條規則中識別出這一點)。 您也不能在否定模式中捕獲組 - 根據定義,否定模式實際上不匹配任何內容。
對於 HTTP 和 HTTPS,第二條規則無條件執行,因為RewriteCond
指令僅適用於RewriteRule
的第一個RewriteRule
。 (但這兩條規則無論如何都可以合二為一。)
要從外部“重定向”(根據您的示例)形式為http://example.com/this-is-old-url/
(或http://example.com/articles/this-is-old-url/
) 到https://example.com/index.php?name=this-is-old-url
然后您可以在.htaccess
文件的頂部執行以下操作:
RewriteCond %{HTTPS} off
RewriteRule ^(?:articles/)?([\w-]+/)$ https://%{HTTP_HOST}/index.php?name=$1 [R=301,L]
更新:正則表達式現在包括-
(連字符)和尾部斜杠。 請注意,尾部斜杠作為捕獲組的一部分包含在內。 因此,它重定向到/index.php?name=this-is-old-url/
(帶有尾部斜杠)。
子模式(?:articles/)?
是可選的和非捕獲的。 因此,這一規則與您的兩個示例 URL 均匹配。
<IfModule>
包裝器不是必需的。 RewriteEngine
指令也不是,因為您可能已經在接下來的 WordPress 代碼塊中使用了它。
您不一定需要公開index.php
,您可以重定向到/?name=...
相反,假設DirectoryIndex
設置正確。
您需要在測試前清除瀏覽器緩存。 (最好先測試 302 - 臨時 - 重定向。)
我無法訪問我的域
https://example.com
,它更改為https://example.com/index.php?name=
。
只有當您請求http://example.com
(注意 HTTP,而不是 HTTPS)時,您現有的規則才不會發生這種情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.