That’s covered as one of the examples in my signature’s tutorial article.
Also, if you’re the webmaster for your site, don’t you know whether mod_rewrite’s enabled or not? In other words, only use <IfModule> blocks if you’re developing for others who may not have mod_rewrite enabled on their servers (because it could cause an endless series of 500 errors) but NEVER make Apache check on your own server - try to speed things up rather than slowing.
Ditto the RewriteBase. If you’re not redirecting (via mod_alias), it has NO PLACE in your mod_rewrite code.
DK,
Thanks for the advice. I went to your tutorial, which is great by the way. The examples came close to what I’m looking for, but example 1 puts the www in front of the subdomain.
I want urls without a subdomain to be enforced to be a www.mydomain.com domain. Urls with a subdomain should not have the www in front of the domain: e.g. intranet.mydomain.com
That’s even simpler (and you had it to begin with - as long as you got rid of the @#$% that was with it)!
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\\.mydomain\\.com [NC]
RewriteRule ^/?(.*)$ http://www.mydomain.com/$1 [R=301,L]
The No Case flag on the RewriteCond statement is because domain names are case insensitive and the /? after the regex start anchor is because Apache 1.x handles the {REQUEST_URI} sting differently than Apache 2.x.
That code works fine for adding the www to the base domain, but that is what I started with and it has always worked fine, even with all the &#&$ that was with it. I need it to enforce www on the root domain AND allow the subdomains to go through without rewriting them or adding the www in front of the subdomain.
Your code is simply saying: “Does the URL have www in front of it?” I want it to say: “If the URL is not a subdomain, then does the URL have a www in front of it” If both conditions are true, then add a www in front of the base URL. If it is a subdomain, leave it as is.
Restated: If there is no subdomain (including www), redirect to www (which will ignore any subdomain because it does not match the condition of the RewriteCond).
RewriteEngine on
RewriteCond %{HTTP_HOST} ^mydomain\\.com$ [NC]
RewriteRule ^/?(.*)$ http://www.mydomain.com/$1 [R=301,L]
I hope I got it right this time and thanks for clarifying!