Force SSL/https using mod_rewrite or PHP

工作需求,要幫某網站全部轉為 HTTPS 加密傳輸。

有兩種方法,一是透過 .htaccess,二是用 PHP 來處理。

用 .htaccess 處理的方式如下

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

用 PHP 來處理:

if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
    if(!headers_sent()) {
        header("Status: 301 Moved Permanently");
        header(sprintf(
            'Location: https://%s%s',
            $_SERVER['HTTP_HOST'],
            $_SERVER['REQUEST_URI']
        ));
        exit();
    }
}

個人比較偏好用 .htaccess 來處理。不過若是沒有全部頁面都需要的話,PHP 比較方便。

 


Posted

in

by

Comments

Leave a Reply

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

Exit mobile version