Forum Moderators: phranque
I am using wildcard subdomains for my site but I want to rewrite all of them to www in apache and can't quite get the code to work. I keep getting a "too many rewrites" error like it is going in a loop.
An example would be:
subd1.mydomain.com -> www.mydomain.com
subdx.mydomain.com -> www.mydomain.com
asd3f.mydomain.com -> www.mydomain.com
I had the following:
RewriteCond %{HTTP_HOST} ^(.*)\.mydomain\.net$
RewriteRule ^/(.*) [mydomain.net...] [R=Permanent,L]
Thanks for any pointers!
You need another RewriteCond that says "only do this for NOT www".
If this code is for .htaccess the leading slash in the Rule must be omitted. For http.conf include it as per your example.
By the way you called this a "rewrite" but in fact it is a "redirect". Big difference :-)
RewriteCond %{HTTP_HOST) !^www\.mydomain\.net
RewriteCond %{HTTP_HOST} ^(.*)\.mydomain\.net$
RewriteRule ^/(.*) [mydomain.net...] [R=Permanent,L]
When I do that it gives me an error and takes me to mydomain.net//////////
Also note I am putting the above in httpd.conf not .htaccess
Thanks for the help!
Also, for efficiency, you should consider using a more-specific subpattern in the second RewriteCond, and getting rid of things that you don't need, such as the back-reference to the subdomain:
RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteCond %{HTTP_HOST} ^[^.]+\.example\.com
RewriteRule ^/(.*) http://www.example.com/$1 [R=301,L]
If you also want to redirect all possible sub-subdomains as well as subdomains, then you can code that as:
RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteCond %{HTTP_HOST} ^([^.]+\.)+example\.com
RewriteRule ^/(.*) http://www.example.com/$1 [R=301,L]
RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteCond %{HTTP_HOST} ^([^.]+\.[b])*e[/b]xample\.com
RewriteRule ^/(.*) http://www.example.com/$1 [R=301,L]
RewriteCond %{HTTP_HOST} !^www\.example\.com$
RewriteRule ^/(.*) http://www.example.com/$1 [R=301,L]
Jim