Sunday, May 26, 2019

Apache用.htaccess來實現強制https訪問

我們可以用Apache的.htaccess的重定向規則來實現http強制跳轉到https訪問網站。

重要提示:必須將代碼放到.htaccess文件內容的最前面,以保證重定向優先權。

代碼如下:

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.domain.com/$1 [R,L]

或者

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.domain.com/$1 [R=301,L]

或者

RewriteEngine on
RewriteBase /
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]

如果是在子目錄,可以用

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} subfolder
RewriteRule ^(.*)$ https://www.domain.com/subfolder [R,L]

將以上代碼複製到.htaccess中即可。

Related Post

2 comments

  1. 我的圖片域名image.yuhaitao.com也配置了一個ssl證書,如何將之前的圖片鏈接都轉換為https://image.yuhaito.com?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.