codeigniter将非www重定向到www

时间:2011-10-05 19:32:34

标签: php .htaccess codeigniter

我看到.htaccess Redirect non-WWW to WWW preserving URI string但它对我不起作用

如果我去 mysite.com/site/something ,我会被重定向到 mysite.com/something

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

也尝试过:

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

修改

这是我使用的代码,基于Alfonso Rubalcava的回答:

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;

}

5 个答案:

答案 0 :(得分:6)

在index.php中尝试开头:

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
}

修改 我读错了你的问题,答案是:

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
}

答案 1 :(得分:2)

在codeigniter的.htaccess文件中包含这两行,将非www url重定向到www

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

即完整的.htaccess文件将是这样的 - >

<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>

答案 2 :(得分:0)

使用此代码

#Redirect to www
RewriteEngine On
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

答案 3 :(得分:0)

我知道,这个问题已经有了公认的解决方案。但是,如果域中还包含一些子域,则会出现问题。如果您的codeigniter也可以处理子域,则这些子域也将重定向到www。

在这种情况下,这就是答案。假设您的域名为www.thedomain.com,代码应为:

$sna = explode(".", $_SERVER['SERVER_NAME']);
if($sna[0]=="thedomain"){
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: http://www.thedomain.com/".$_SERVER['REQUEST_URI']);
}

答案 4 :(得分:0)

您可以在所有codeigniter网站中使用以下代码。

`

<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>

`