Reputation: 13
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:
Upvotes: 1
Views: 128
Reputation: 786359
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]
Upvotes: 1