.htaccessisapi-rewrite

Redirecting non-www URL to www using .htaccess


I'm using Helicon's ISAPI Rewrite 3, which basically enables .htaccess in IIS. I need to redirect a non-www URL to the www version, i.e. example.com should redirect to www.example.com. I used the following rule from the examples but it affects subdomains:

RewriteCond %{HTTPS} (on)?
RewriteCond %{HTTP:Host} ^(?!www\.)(.+)$ [NC]
RewriteCond %{REQUEST_URI} (.+)
RewriteRule .? http(?%1s)://www.%2%3 [R=301,L]

This works for most part, but is also redirect sub.example.com to www.sub.example.com. How can I rewrite the above rule so that subdomains do not get redirected?


Solution

  • Append the following RewriteCond:

    RewriteCond %{HTTP:Host} ^[^.]+\.[a-z]{2,5}$ [NC]
    

    That way it'll only apply the rule to nondottedsomething.uptofiveletters as you can see, subdomain.domain.com will not match the condition and thus will not be rewritten.

    You can change [a-z]{2,5} for a stricter tld matching regex, as well as placing all the constraints for allowed chars in domain names (as [^.]+ is more permissive than strictly necessary).

    All in all I think in this case that wouldn't be necessary.

    EDIT: sadie spotted a flaw on the regex, changed the first part of it from [^.] to [^.]+