Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 656
chrisofspades Avatar asked Sep 08 '08 23:09

chrisofspades


2 Answers

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 [^.]+

like image 170
Vinko Vrsalovic Avatar answered Sep 18 '22 17:09

Vinko Vrsalovic


I've gotten more control using urlrewriter.net, something like:

<unless header="Host" match="^www\.">
   <if url="^(https?://)[^/]*(.*)$">
     <redirect to="$1www.domain.tld$2"/>
   </if>
   <redirect url="^(.*)$" to="http://www.domain.tld$1"/>
</unless>
like image 38
dlamblin Avatar answered Sep 20 '22 17:09

dlamblin