2016-09-13 20 views
1

我想實現99%的工作,但有一個小問題。HTACCESS 301重定向規則指向實時URL的所有URL變化

比方說,我活的URL是https://www.example.com/sample-page/

我希望所有的以下網址的變化重定向到URL直播與301個狀態。

http://example.com/sample-page/ 
http://www.example.com/sample-page/ 
https://example.com/sample-page/ 

的上述所有應該重定向到https://www.example.com/sample-page/

我設法通過下面顯示的htaccess的規則得到這個工作。

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] 

上述規則的問題是:http://example.com/sample-page/做雙重定向。

http://eyeacademy.com/expert-eye-examination/ 
301 Moved Permanently 
https://eyeacademy.com/expert-eye-examination/ 
301 Moved Permanently 
https://www.eyeacademy.com/expert-eye-examination/ 
200 OK 

正如您所看到的,http重定向到https,然後https非www重定向到https www。我一直在嘗試對這個規則進行一些調整,然後閱讀,但我相信這裏有人會有更快更強大的解決方案?

+0

把https規則最後? – 123

+0

試過了。它通過添加www.www來打破https非www網址。到域。 –

+0

以'L'取代第一條規則。 – 123

回答

3

您可以使用此單一規則重定向http -> https,並添加www並沒有必要在規則中硬編碼的主機名:

RewriteCond %{HTTP_HOST} !^www\. [NC,OR] 
RewriteCond %{HTTPS} off 
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] 
RewriteRule^https://www.%1%{REQUEST_URI} [L,R=301,NE] 

您也可以重新排序現有的規則,並避免像這樣的多重定向:

# first add www and make sure it is https:// 
RewriteCond %{HTTP_HOST} !^www\. [NC] 
RewriteRule^https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE] 

# http -> https 
RewriteCond %{HTTPS} off 
RewriteRule^https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE] 
+1

謝謝。第一個選項有效。我也會嘗試第二個。 –

+1

這兩個解決方案都很完美!謝謝! –

+1

[見此](http://www.regular-expressions.info/brackets.html)和標題**非捕獲組** – anubhava

1

在您的RewriteCond指令中使用or標誌。具有下列取代一切:

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

建議的解決方案應該是'HTTP_HOST'不可知的 – freedev

+0

@freedev爲什麼? OP沒有提到這樣的要求。無論如何,一個通用的重定向也不應該很難實現。 – hjpotter92

+0

@freedev提出了一個很好的觀點。 –