Codeigniter SSL 强制重定向至https访问
有两种方法:
1、方法一: 修改.htaccess
RewriteEngine on
ReWriteCond %{SERVER_PORT} !^443$
RewriteRule ^/(.*) https://%{HTTP_HOST}/index.php/$1 [NC,R,L]
并且修改application/config/config.php文件:
$config['base_url'] = 'https://www.my-site.com/';
但是这种方法url会出现index.php,所以推荐法二。
2、方法二:使用codeigniter中的hook函数
打开文件application/config/config.php,并且设置hooks为TRUE
$config['enable_hooks'] = TRUE;
修改application/config/hooks.php,添加以下内容:
$hook['post_controller_constructor'][] = array(
'function' => 'redirect_ssl',
'filename' => 'ssl.php',
'filepath' => 'hooks'
);
创建文件application/hooks/ssl.php,并且添加以下内容:
<?php
/**
*
* Author : Tony Liu
* Blog: https://www.tonyblog.cn
*
* @package Codeigniter
*/
/**
*SSL Redirect Config Function
*/
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());
}
}
OK,配置好了,就可以重定向至https访问了。
Related Issues not found
Please contact @tonyabm to initialize the comment