.htaccess non-www to www redirect

Discussion in 'Apache' started by Pipuks, Feb 19, 2010.

  1. #1
    I'm trying to set up non-www to www redirect using .htaccess. This is a simple task, but the problem I have is that I'm running http and https versions under the same domain.

    
    RewriteCond %{HTTP_HOST} ^mydomain.com [NC]
    RewriteRule ^(.*)$ http://www.mydomain.com/$1 [L,R=301]
    
    Code (markup):
    The code above does a nice job for http version, but when https://mydomain.com/ is called it is redirected to http://www.mydomain.com/

    I've modified it a bit and the .htaccess file now looks like this:

    
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} ^mydomain.com [NC]
    RewriteRule ^(.*)$ http://www.mydomain.com/$1 [L,R=301]
    
    RewriteCond %{HTTPS} on
    RewriteCond %{HTTP_HOST} ^mydomain.com [NC]
    RewriteRule ^(.*)$ https://www.mydomain.com/$1 [L,R=301]
    
    Code (markup):
    I was wondering if there is a more sophisticated way to accomplish this task as I don't really like having both of these blocks in my .htaccess.

    Any recommendations?
     
    Last edited: Feb 19, 2010
    Pipuks, Feb 19, 2010 IP
  2. MrYu

    MrYu Peon

    Messages:
    157
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Why don't you like this? It's not broken, so leave it be...

    You can play around with %{SERVER_PORT} 443 and not 443, but in the end you'll get about the same number of lines and it's less certain about HTTPS, too -- http can be served on 443 without SSL.
     
    MrYu, Feb 27, 2010 IP
  3. nadlerz

    nadlerz Well-Known Member

    Messages:
    264
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    188