1

There are a few questions like this, but my question is a little different

Redirect non-www to www in .htaccess

force non www to www in htaccess

Redirect Non-WWW to WWW URLs

I want to redirect the non-www version of the website to www, but it should not in any way effect the subdomains, so

www.example.com => www.example.com
example.com => www.example.com
sub1.example.com => sub1.example.com
sub2.example.com => sub2.example.com

this does not work, cause it does not behave good in case of subdomains

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

This solution works fine

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

however, the important thing is I do not want to hardcode the domain name in htacess. How to (if even possible) have the above mentioned redirections for general case - without mentioned the exact domain name ?

Thanks

Community
  • 1
  • 1
dav
  • 8,931
  • 15
  • 76
  • 140

1 Answers1

1

You can use this rule:

RewriteCond %{HTTP_HOST} ^[^.]+\.com(\.au)?$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • tks for the asnwer: it did not work, but maybe it is because of I have domain `example.com.au` ? is it possible to make it work both with `example.com` and `example.com.au` types of domains ? – dav Jun 13 '15 at 09:57
  • it worked, but can we generalize the com and au part ? I mean I tried like this `RewriteCond %{HTTP_HOST} ^[^.]+\.[a-z]{2,3}(\.[a-z]{2})?$ [NC]`, and it worked, but is it correct syntax ? tks – dav Jun 13 '15 at 10:04
  • Hmm your regex is not 100% foolproof to detect non-subdomains. For ex it will match `bbc.co.uk` which is a subdomain. – anubhava Jun 13 '15 at 10:07
  • 1
    ok, i see, anyway this is good enough to go with, thanks for ur help and time ))) – dav Jun 13 '15 at 10:10