我需要example.com被重定向到https://www.example.com.
我的 .htaccess 檔案位于根目錄中,配置如下:
RewriteEngine On
DirectoryIndex html/home5.html
RewriteRule ^\.htaccess$ - [F]
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
使用此配置,www.example.com,https://example.com和http://example.com都正確重定向到https://www.example.com(www.example.com/other.html以此類推)。
但是example.com被重定向到https://www.example.com/http://www.example.com/并顯然會產生“在此服務器上找不到請求的 URL”。為什么會發生這種情況?我需要改變什么才能使它作業?
我也鴕鳥政策明白為什么我的當前配置https://example.com的www正確添加。
uj5u.com熱心網友回復:
重定向到 https 和非 www
要將所有請求重定向到 https 和非 www,請使用以下代碼而不是之前的代碼:
規范的 HTTPS/非 WWW
<IfModule mod_rewrite.c>
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule (.*) https://example.com/$1 [L,R=301]
</IfModule>
和以前一樣,將此代碼放在您網站的根目錄 .htaccess 中。這是它在做什么:
Checks if mod_rewrite is available
Checks if HTTPS is off, or if the request includes www
If either condition matches, the request qualifies and is redirected to the https/non-www address
當放置在根 .htaccess 中時,此技術涵蓋所有請求,為您的站點提供完整的 https/non-www 規范化。請記住將 example.com 的兩個實體替換為您自己的域名。
注意:如果您的網站因為 index.php 附加到請求的 URL 而遭受重復頁面的困擾,請查看 WP-Mix.com 上的這篇文章,其中解釋了如何從 URL 中洗掉 www 和 index.php。重定向到 https 和 www
以下 .htaccess 技術將符合條件的請求重定向到您網頁的 https 和 www 版本。添加到您網站的根 .htaccess 檔案中:
規范的 https/www
<IfModule mod_rewrite.c>
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule (.*) https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
此代碼執行以下操作:
The first two lines conditionally redirect to https. If the HTTPS variable is set to off, then the request is redirected to https (see notes below if using a proxy).
The second two lines redirect to www. If the request/host does not begin with www., the request is redirected to www.
當放置在根 .htaccess 中時,此技術涵蓋所有請求,為您的站點提供完整的 https/www 規范化。此代碼無需編輯;它完全是即插即用的。使用代理時的注意事項
正如這里所解釋的:
“在某些形式的代理背后,即客戶端通過 HTTPS 連接到代理、負載均衡器、Passenger 應用程式等時,%{HTTPS} 變數可能永遠不會打開并導致重寫回圈。這是因為您的應用程式是即使客戶端和代理/負載均衡器使用 HTTPS,實際接收到普通的 HTTP 流量。在這些情況下,檢查 X-Forwarded-Proto 標頭而不是 %{HTTPS} 變數。”
因此,如果您使用某種代理服務或類似服務,請將以下行添加到上述代碼中:
RewriteCond %{HTTP:X-Forwarded-Proto} !https
所以如果使用代理服務器,最終結果如下所示:
規范的 https/www(使用代理時)
<IfModule mod_rewrite.c>
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule (.*) https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
參考
uj5u.com熱心網友回復:
得到了一個運行良好的 .htacces 我正在使用相同的問題,有 2 個步驟:
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]
首先,如果請求的 url 被 HTTPS “關閉”,則重定向到 HTTPS 并在之后添加 url 請求查詢(保存在 $1 中)。
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%1/$1 [L]
然后,www 的特殊情況。子域和 https 打開,如果在請求中匹配“www”,則重定向到 https 打開的同一頁面!
編輯:實際上你甚至不需要第二個條件
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/316588.html
