1

I am using a shared codebase to support several domains, and I want to force the use of a www subdomain in .htaccess, replacing any other subdomain provided without otherwise altering the HTTP_HOST.

I've read several solutions on how to force www when a subdomain is not provided (e.g. example.com becomes www.example.com) and how to add www to the beginning of the HTTP_HOST (e.g. test.example.com becomes www.test.example.com). What I have NOT found is how to replace ANY subdomain (or lack thereof) with www while keeping the first and second level domains intact, whatever they might be.

I need a generic rule that will make all of the following rewrites (as 301s) without having to write rules for every TLD and every possible subdomain:

  • example.com => www.example.com
  • test.example.com => www.example.com
  • example.ca => www.example.ca
  • blog.example.ca => www.example.ca
  • example.be => www.example.be
  • users.example.be => www.example.be
  • example.co.uk => www.example.co.uk
  • users.example.co.uk => www.example.co.uk
anubhava
  • 761,203
  • 64
  • 569
  • 643
Unicycle
  • 13
  • 5
  • you mean this? http://stackoverflow.com/questions/1157255/how-to-redirect-non-www-to-www-urls-using-htaccess edit: nope – rasso Jul 13 '15 at 17:33

1 Answers1

1

You can use this rule for all the cases:

RewriteEngine on

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:[^.]+\.)?(example\..+)$ [NC]
RewriteRule ^ http://www.%1%{REQUEST_URI} [R=301,L,NE]
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Thanks for this! I was able to build off it for what I needed. What I couldn't get to work from your answer was the pipe in the second line. Instead, I went with RewriteCond %{HTTP_HOST} (?:^[^.]*\.)(example\..+)$ [NC]. Any danger in that? – Unicycle Jul 16 '15 at 18:34
  • Nope that's good enough and should work.. let me update the answer – anubhava Jul 16 '15 at 18:37