2011-10-05 104 views
4

我看到.htaccess Redirect non-WWW to WWW preserving URI string但它並不適合我笨非www重定向到www

工作,如果我去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] 

編輯:

這裏使用的代碼即時通訊的基礎上,阿方索·魯瓦爾卡瓦的回答是:

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; 

} 
+0

此「// site /」看起來像格式不正確的鏈接。您可能希望在代碼中進行更正(在視圖中?)以避免搜索引擎將其編入索引。 –

+0

哦..鏈接沒有格式錯誤,必須是CI路由或htaccess的東西去除index.php ..行爲是相同的,當我在瀏覽器上輸入地址 – braindamage

+0

'http://www.site.com //網站/'? –

回答

3

嘗試,在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

我不能這樣做只使用htaccess? – braindamage

+0

是的,你可以。這只是一種用更熟悉,更少問題的方式來做到這一點......並且每次從服務器遷移時都不需要進行調整。 –

+0

謝謝,它的工作..btw我刪除了「else」語句,並使用「退出」在最後的if:] – braindamage

1

包括笨到非www URL重定向到www

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

的.htaccess文件這兩條線即滿.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> 
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]