簡體   English   中英

始終使用htaccess通過www優化重定向到https

[英]Redirect to https always with www optimization using htaccess

我需要將所有內容重定向到我的域以使用https:// www ,以下是我當前使用的.htaccess:

RewriteCond %{HTTPS} off
# First rewrite to HTTPS:
# Don't put www. here. If it is already there it will be included, if not
# the subsequent rule will catch it.
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Now, rewrite any request to the wrong domain to use www.
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

它正在工作,但是如果沒有www,它將進行兩次重定向到瀏覽器;如果缺少安全性,則進行第二次重定向,這當然很慢並且可能很糟糕。

我想要的還是我的問題是,可以將其簡化為單個重定向規則,以使其在一個規則中同時添加www和https。

此在線測試工具顯示了2個重定向https://varvy.com/tools/

Final status code: 200
2 Redirect(s)
http://domain.com
301 redirect
https://domain.com/
https://domain.com/
301 redirect
https://www.domain.com/

對此代碼進行任何好的優化。

您可以使用:

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]

2條規則,但不能超過一個重定向

您只能使用1條規則

RewriteEngine On

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

這里不需要非www到www重定向,因為您要將兩個版本都重定向到https:// www

在測試之前,請清除瀏覽器的緩存。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM