Search code examples
phpcodeignitersessionhttp-redirectno-www

CodeIgniter - How to redirect into non WWW URL with sessions


In my CodeIgniter project, when I try to redirect from one controller to some other controller/function, An extra "WWW" comes just in front of the URL. With that WWW-URL, I can't access my old session information created in the non-WWW site.

my redirect code is below.

public function test()
{
    $this->load->helper('url');
    redirect('/Cat/view');
}

the URL looks like below

http://app.mysite.com/login                   << where I set session info
http://www.app.mysite.com/index.php/Cat/View  << After redirect

how can redirect from non-www site to non-www site safely in CodeIgnitor?


Solution

  • I got the issue fixed by modifying my .htaccess file to rewrite the URL without WWW if it is there.

    The first part of the below code is to remove "WWW" and the second part is to remove "index.php" from the URL

    DirectoryIndex index.php
    
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
    
    RewriteCond $1 !^(index\.php|robots\.txt|favicon\.ico)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]