Forum Moderators: phranque

Message Too Old, No Replies

.htaccess Redirect for non WWW to WWW Domains

         

rjrufo

2:42 pm on May 9, 2005 (gmt 0)

10+ Year Member



I tried searching for an answer, but it seems that the search function in the forums doesn't work right now.

My question is: is it possible to redirect non www domains to www domains without writing a rule for every domain name on the server?

For example, example1.com, example2.net, and example3.org needs to be redirected to www.example1.com, www.example2.net, and www.example3.org respectivly, but hopefully without the need to write a rule each.

So, in the above example, when a new domain name is registered: example4.info it automatically gets redirected to www.example4.info.

After searching the internet and these forums, I believe that something like this would work:


RewriteEngine on
RewriteCond %{HTTP_HOST}!^(www\.*\.*) [NC]
RewriteRule (.+) http://www.*.*/$1 [R=301,L]

but I wanted to make sure before trying it.

jdMorgan

4:13 pm on May 9, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You'll need to extract the domain name, and then back-reference it in the Rule. Here's one way to do it:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(.+)\.com [NC]
RewriteRule (.*) http://www.%1.com/$1 [R=301,L]

See our forum charter [webmasterworld.com] for references on mod_rewrite and regular expressions.

Jim