[英]How to force ssl in codeigniter?
我正在使用 codeigniter 3. 如何強制 SSL 連接到我的網頁,以便所有頁面都加載了旁邊的綠色掛鎖圖標?
注意:如何在不必編輯 htaccess 文件的情況下執行此操作?
從位置application/config/config.php
打開配置文件,並像這樣啟用或設置鈎子為 true:
$config['enable_hooks'] = TRUE;
然后在config
文件夾(即application/config/hooks.php)中新建一個名為hooks.php
的文件,並在其中添加如下代碼:
$hook['post_controller_constructor'][] = array(
'function' => 'redirect_ssl',
'filename' => 'ssl.php',
'filepath' => 'hooks'
);
現在在application
文件夾中創建一個名為hooks
的新目錄(即 application/hooks),然后在hooks
文件夾中創建一個名為ssl.php
的新文件(即 application/hooks/ssl.php)。
在ssl.php
文件中添加以下代碼:
function redirect_ssl() {
$CI =& get_instance();
$class = $CI->router->fetch_class();
$exclude = array('client'); // add more controller name to exclude ssl.
if(!in_array($class,$exclude)) {
// redirecting to ssl.
$CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
if ($_SERVER['SERVER_PORT'] != 443) redirect($CI->uri->uri_string());
} else {
// redirecting with no ssl.
$CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
if ($_SERVER['SERVER_PORT'] == 443) redirect($CI->uri->uri_string());
}
}
在您的配置中更改base_url
:
$config['base_url'] = 'https://www.my-site.com/';
將傳入流量從http
重定向到https
:
RewriteCond %{HTTPS} off RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Codeigniter(GAE) :在 ssl.php 文件中將 http 重定向到 https 的最佳實踐:
function force_ssl() {
$server=$_SERVER["SERVER_NAME"];
$uri=$_SERVER["REQUEST_URI"];
if ($_SERVER['HTTPS'] == 'off') {
redirect("https://{$server}{$uri}");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.