force https www for codeigniter in htaccess with mod rewrite

force https www for codeigniter in htaccess with mod rewrite  using -'php,.htaccess,codeigniter,mod-rewrite'

I'm using Codeigniter and following these instructions to force ssl but all requests are being redirected to

My .htaccess is:

### Canonicalize codeigniter URLs

# Enforce SSL https://www.
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Removes access to the system folder by users.
# Additionally this will allow you to create a System.php controller,
# previously this would not have been possible.
# 'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php/$1 [L]

# Checks to see if the user is attempting to access a valid file,
# such as an image or css document, if this isn't true it sends the
# request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]


asked Sep 15, 2015 by NStjohn
0 votes

4 Answers

0 votes

I think, instead of

RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

you should have something like

RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

do have the rewrite rule match. Your link is currently produced by the third rule.

answered Sep 15, 2015 by AdrienneMchu
0 votes

You could do it in code instead of using htaccess.

You can create a helper function that will redirect the page to be over SSL, which you call from your controller.

In your helper;

function force_ssl() {
    if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") {
        $url = "https://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];

Then in your controller;

class Whatever extends CI_Controller {

    function __construct() {

    public function index() {
answered Sep 15, 2015 by CorneliusMed
0 votes

Use this

RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$$1 [R=301,L]

instead of

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
answered Sep 15, 2015 by CynWhitefoo
0 votes

Presumably you have RewriteEngine On somewhere above this code...

RewriteCond %{REQUEST_URI} ^system.*

probably isn't going to be triggered. REQUEST_URI should start with / (unlike RewriteRule), so you probably want

RewriteCond %{REQUEST_URI} ^/system

I'm not sure that

RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

will reliably match, with ^. I would try the following:

RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [L,R=301]

Incidentally, HTTP_HOST is normally whatever the visitor typed in, so www. is not guaranteed, if that's what you want. You will need a separate step to force www..

answered Sep 15, 2015 by HilIredale