Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

codeigniter redirect non-www to www

i saw .htaccess Redirect non-WWW to WWW preserving URI string but it doesn't work for me

if i go to mysite.com/site/something i get redirected to mysite.com/something

RewriteCond %{HTTP_HOST} !^www\.mysite\.com$
RewriteRule (.*) http://www.mysite.com/$1 [R=301,L]

also tried:

RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www.mysite.com [NC]
RewriteRule (.*) http://www.mysite.com/$1 [R=301,L]

edit:

here's the code im using, based on Alfonso Rubalcava's answer:

if (substr($_SERVER['SERVER_NAME'], 0, 3) != 'www')
{

    if ($_SERVER['REQUEST_URI'] == '//site/')
    {
        header('HTTP/1.1 301 Moved Permanently');
        header('Location: http://www.site.com/site/');
        exit;
    }

    header('HTTP/1.1 301 Moved Permanently');
    header('Location: http://www.site.com' . $_SERVER['REQUEST_URI']);
    exit;

}
like image 774
braindamage Avatar asked Oct 05 '11 19:10

braindamage


3 Answers

Try, in index.php, at the beginning:

if(substr($_SERVER['SERVER_NAME'],0,3)=="www"){
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: http://yourdomain.tdl/".$_SERVER['REQUEST_URI']);
}else{
    //the current contents of your file
}

EDIT I read your question wrong, the answer is:

if(substr($_SERVER['SERVER_NAME'],0,3)!="www"){
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: http://www.yourdomain.tdl/".$_SERVER['REQUEST_URI']);
}else{
    //the current contents of your file
}
like image 132
Alfonso Rubalcava Avatar answered Oct 14 '22 14:10

Alfonso Rubalcava


include these two lines in the .htaccess file of codeigniter to redirect non-www url to www

RewriteCond %{HTTP_HOST} !^www\.(.*)
RewriteRule (.*) http://www.%{HTTP_HOST}/$1 [R=301,L]

i.e the full .htaccess file will be something like that->

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{HTTP_HOST} !^www\.(.*)
 RewriteRule (.*) http://www.%{HTTP_HOST}/$1 [R=301,L]
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
like image 4
srv Avatar answered Oct 14 '22 15:10

srv


Use this code

#Redirect to www
RewriteEngine On
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
like image 1
RN Kushwaha Avatar answered Oct 14 '22 14:10

RN Kushwaha