0

I'm trying to force redirect to www with https from index.php but i keep getting an infinite redirect loop.

Here is my code:

index.php:

$configs = include_once($_SERVER['DOCUMENT_ROOT'] . '/application/config/maintenance.php');

if (stripos($_SERVER['SERVER_PROTOCOL'], 'https') === false && $configs['protocol'] == 'https') {
    $protocol = 'https://';
    $protocolRedirect = true;
} else {
    $protocol = 'http://';
    $protocolRedirect = false;
}

if (strtolower(substr($_SERVER['HTTP_HOST'], 0, 4)) !== 'www.') {
    $url = $protocol . 'www.' . $_SERVER['HTTP_HOST'];
    $wwwRedirect = true;
} else {
    $url = $protocol . $_SERVER['HTTP_HOST'];
    $wwwRedirect = false;
}

if ($_SERVER['REQUEST_URI'] != '/') {
    $url .= $_SERVER['REQUEST_URI'];
}

if ((isset($wwwRedirect) && $wwwRedirect == true) || (isset($protocolRedirect) && $protocolRedirect == true )) {
    header('Location: ' . $url);
    exit();
}

maintenance.php:

return array(
    'protocol' => 'https'
);

Any idea why?

Note: server is running Nginx - but i don't want to redirect thorugh it.

FireBrand
  • 463
  • 5
  • 16
  • 1
    Hi, i hpe this topic can helpyou [link](http://stackoverflow.com/questions/1500527/how-can-i-have-codeigniter-load-specific-pages-using-ssl) – elddenmedio Apr 19 '16 at 17:06
  • I think this could be simpler: `if(strtolower(substr(explode('.', $_SERVER['HTTP_HOST'])[0], -3, 3)) !== 'www'){ /* redirect */ }` – MonkeyZeus Apr 19 '16 at 17:07
  • Check if `$_SERVER['HTTPS']` exists and is set to `On`. `SERVER_PROTOCOL` can never have `HTTPS`. – Charlotte Dunois Apr 19 '16 at 17:09
  • 1
    In fact if you connect over the web to PHP all you'll ever get in server protocol is `HTTP/(HTTP-Version)`, commonly `HTTP/1.1` or `HTTP/2` – Charlotte Dunois Apr 19 '16 at 17:16
  • What version of Codeigniter? – DFriend Apr 19 '16 at 18:09
  • Did you consider of solution with `.htaccess` Apache file instead? Then, everything you should do with CI is set `base_url() === 'https://www.example.com/'`. – Tpojka Apr 19 '16 at 21:01
  • if you have set up SSL properly server side, why not simply set your `$config['base_url']` to `https://site` ? – Kisaragi Apr 20 '16 at 02:20
  • @CharlotteDunois - I have a different project that uses `SERVER_PROTOCOL` so i don't understand why that didn't work, do you have a link to the explanation? @DFriend - 3.0.4 @Tpojka - as i wrote, i'm not using `Apache`, i'm using `Nginx` @Kisaragi - that won't redirect, also i need to be able to move from `https` back to `http` to be able to work on the dev server – FireBrand Apr 20 '16 at 07:33

0 Answers0