2017-09-23 63 views
0

我想我的域名HTTP重定向到https,我已經做到這一點與下面提及的代碼如何domain.com或者www.domain.com重定向到https www.domain.com

RewriteEngine on 
RewriteCond %{HTTP_HOST} ^domain.com [NC] 
RewriteRule ^(.*)$ https www.domain.com/$1 [L,R=301,NC] 

當用戶輸入domain.com它會自動重定向到https www.domain.com但是當用戶只輸入www.domain.com它重定向到http www.domain.com

請幫我解決這個問題。

+0

這爲我工作[非www到https www重定向](https://stackoverflow.com/questions/17453412/redirect-to-http-non-www-to-https-www-htaccess/31234149#31234149) –

回答

0

您可以使用:

RewriteEngine on 
# Test without www 
RewriteCond %{HTTP_HOST} !^www\. [OR,NC] 
# Test for http 
RewriteCond %{HTTPS} off 
# Redirect to https www 
RewriteRule^https://www.exemple.com%{REQUEST_URI} [NE,R=301,L] 
0

在你的代碼:

RewriteCond %{HTTP_HOST} ^domain.com [NC] 

它是以下規則的條件;所以該規則將僅適用於無www請求。

此外,在測試新代碼時不要使用R=301重定向,除非您確定規則正常,並且您可以使用R=302或僅使用R

不管你的代碼將下面的代碼在你的主目錄.htaccess的:

RewriteEngine On 
RewriteCond %{HTTPS} !=on 
RewriteRule^https://%{HTTP_HOST}%{REQUEST_URI} [L,R] 

如果要強制每個請求是www你應該這樣做:

RewriteEngine On 

RewriteCond %{HTTPS} !=on 
#this line above will match any request without `https` 

RewriteCond %{HTTP_HOST} ^www\. [NC] 
RewriteRule^https://%{HTTP_HOST}%{REQUEST_URI} [L,R] 

#the two lines above will exclude none `www` request and force only `www` request unto `https` and the rule will stop here `L` 

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

# the last two line will exclude any `www` request and force only none `www` into `https` 
相關問題