How to dynamically redirect non-www to www.?

Discussion in 'Apache' started by Pros, Jan 16, 2010.

  1. #1
    I am wondering what code (if it is possible) I would use in my .htaccess file to be able to dynamically send all non-www traffic on my domain to www.

    By dynamically I mean like this:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
    RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
    Code (markup):
    Except that I would not have to type in which domain I wanted to use it on: I could use the one piece of code on any domain.

    If anyone could help me figure this out, I would be most appreciative.

    Thank you.
     
    Pros, Jan 16, 2010 IP
  2. tolra

    tolra Active Member

    Messages:
    515
    Likes Received:
    36
    Best Answers:
    1
    Trophy Points:
    80
    #2
    If you mean you have many domains pointing to the same webspace and want them all to redirect to the www version of specific domain then:
    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
    RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
    
    Code (markup):
    If you want all non-www to redirect to www but without having to put the domain name in .htaccess:
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^(?!www\.)(.*)$ [NC]
    RewriteRule (.*) http://www.%1/$1 [R=301,L]
    
    Code (markup):
    If you want all www to redirect to non-www but without having to put the domain name in .htaccess:
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule (.*) http://%1/$1 [R=301,L]
    
    Code (markup):
    I checked the last 2 on our shared hosting servers which run Apache 2.2 and they worked fine in the limited testing I did.
     
    tolra, Jan 16, 2010 IP
  3. Pros

    Pros Well-Known Member

    Messages:
    244
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    150
    #3
    Working absolutely perfectly! Extremely valuable post, thank you! Wish I could rep you twice :)
     
    Pros, Jan 19, 2010 IP