Tony's Blog

Codeigniter SSL 强制重定向至https访问

有两种方法:

1、方法一: 修改.htaccess

  1. RewriteEngine on
  2. ReWriteCond %{SERVER_PORT} !^443$
  3. RewriteRule ^/(.*) https://%{HTTP_HOST}/index.php/$1 [NC,R,L]

并且修改application/config/config.php文件:

  1. $config['base_url'] = 'https://www.my-site.com/';

但是这种方法url会出现index.php,所以推荐法二。

2、方法二:使用codeigniter中的hook函数

打开文件application/config/config.php,并且设置hooks为TRUE

  1. $config['enable_hooks'] = TRUE;

修改application/config/hooks.php,添加以下内容:

  1. $hook['post_controller_constructor'][] = array(
  2. 'function' => 'redirect_ssl',
  3. 'filename' => 'ssl.php',
  4. 'filepath' => 'hooks'
  5. );

创建文件application/hooks/ssl.php,并且添加以下内容:

  1. <?php
  2. /**
  3. *
  4. * Author : Tony Liu
  5. * Blog: https://www.abmbio.xin
  6. *
  7. * @package Codeigniter
  8. */
  9. /**
  10. *SSL Redirect Config Function
  11. */
  12. function redirect_ssl() {
  13. $CI =& get_instance();
  14. $class = $CI->router->fetch_class();
  15. $exclude = array('client'); // add more controller name to exclude ssl.
  16. if(!in_array($class,$exclude)) {
  17. // redirecting to ssl.
  18. $CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
  19. if ($_SERVER['SERVER_PORT'] != 443) redirect($CI->uri->uri_string());
  20. } else {
  21. // redirecting with no ssl.
  22. $CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
  23. if ($_SERVER['SERVER_PORT'] == 443) redirect($CI->uri->uri_string());
  24. }
  25. }

OK,配置好了,就可以重定向至https访问了。