
CakePHPでSSLでの接続をしなくてはいけなくて
CakePHPでその設定をしてみました。
すべてのページでSSL接続を強制する
すべてのページでSSLを常時接続するので
設定としては簡単にできます。
Controller/AppController.php
public $components = array(
'Security'
);
public function beforeFilter() {
// HTTP でない場合に実行するメソッド名
$this->Security->blackHoleCallback = 'forceSecure';
// 全てのアクション
$this->Security->requireSecure();
}
public function forceSecure() {
$this->redirect("https://".env('SERVER_NAME').$this->here);
}
まずは、AppController.phpに
Security Component を使うように $components に追加します。
Controller/AppController.php
public $components = array(
'Security'
);
上記のように設定を書きます。
次にHTTPSに強制的に接続を変えます。
public function beforeFilter() {
// HTTP でない場合に実行するメソッド名
$this->Security->blackHoleCallback = 'forceSecure';
// 全てのアクション
$this->Security->requireSecure();
}
equireSecure()で HTTPS を強制したいアクションを指定します。
requireSecure() に引数を入れなければコントローラの全てのアクションを
SSL接続に変えることができます。
次にbeforeFilter()の下にHTTPで接続した場合に
同じアクションにHTTPSでリダイレクトするようにします。
public function forceSecure() {
$this->redirect("https://".env('SERVER_NAME').$this->here);
}
こうするとお気に入りとかでHTTPのままのショートカットでも
HTTPSに接続が変更されます。
今回はすべてのページでSSL接続したかったので
AppController.phpに書きました。
個別で指定したい場合
各ページでSSLを設定したい場合は
各コントローラーで最初にやった内容を記述すればいいみたいです。
PostsControllerをSSL接続する場合
Controller/PostsController.php
class PostsController extends AppController {
public $components = array('Security');
public function beforeFilter(){
//SSLを強制するアクションを設定
$this->Security->requireSecure(array('add', 'edit'));
}
public function forceSSL() {
$this->redirect('https://' . env('SERVER_NAME') . $this->here);
}
public function add() {
}
public function edit() {
}
}
こんな感じで、各コントローラー毎にアクションを指定すればいいみたい。
(参考)
[CakePHP2] Security Component を使って SSL を強制する
CakePHP2.xでSSL接続(https://)を強制させる
CakePHPのSSL Componentでhttpとhttpsを切り替えるAdd Star
