301 Redirect for no-www to www

Discussion in 'Site & Server Administration' started by ArtfulWebSites, Mar 14, 2007.

  1. #1
    Ok, I have a virtual host account with one Primary Domain in the Root folder and several Secondary Domains in sub-folders.

    For consolidation of Google Page Ranking and avoidance of any possible duplicate content problems with referrals to Domain.com vs www.Domain.com, I have made a master .htaccess file that I copy to EACH Domain's folder to 301 Redirect any reference to Domain.com to www.Domain.com.

    It all works fine. I currently have it coded as:

    RewriteEngine on
    Options +ExecCGI
    rewritecond %{http_host} ^Domain1.com [nc]
    rewriterule ^(.*)$ http://www.Domain1.com/$1 [r=301,nc]

    rewritecond %{http_host} ^Domain2.com [nc]
    rewriterule ^(.*)$ http://www.Domain2.com/$1 [r=301,nc]

    rewritecond %{http_host} ^Domain3.com [nc]
    rewriterule ^(.*)$ http://www.Domain3.com/$1 [r=301,nc]
    ...Etc.

    I suspect with the proper wild-card coding, I could consolidate the multiple redirect directives into one that would say "redirect [AnyDomain].com to www.[AnyDomain].com", but I am not sure how to code this correctly. Since all the sites are live, I don't want to screw it up.

    Anyone out there know how to code that properly???
     
    ArtfulWebSites, Mar 14, 2007 IP
  2. rodney88

    rodney88 Guest

    Messages:
    480
    Likes Received:
    37
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You need to match the host against a pattern not starting in www, then redirect every request to include www.
    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301]
    Code (markup):
    Note that will also apply to sub.domain.com, redirecting to www.sub.domain.com

    If you want to test redirections, always use the R without =301 so that by default, it will send a 302 "temporarily moved" header. A browser might store the new location for the "permanently moved" (301) page and the next time you request the old location, automatically redirect without making a request to your server.

    When you know it's working, then make it a 301.
     
    rodney88, Mar 15, 2007 IP
  3. ArtfulWebSites

    ArtfulWebSites Peon

    Messages:
    130
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Rod,

    Thanks so much. That looks like exactly what I need. I will try it straight away. :D
     
    ArtfulWebSites, Mar 15, 2007 IP