There are plenty of examples here of how to redirect example.com to www.example.com, but I'm looking for a generic version, so the same htacess code would also work to redirect example.net to www.example.net and example.org to www.example.org. I'm sure this exists (indeed, I have a vague memory I've done it before, somewhere), but I'm fairly unfamiliar with htaccess regex.

I need a way to match the condition HTTP_HOST does not begin with www..

link|improve this question

50% accept rate
feedback

2 Answers

#Enable RewriteEngine
RewriteEngine On

# For a way to check HTTP_HOST not beginning with www:    
RewriteCond %{HTTP_HOST} !^www [nc]

# As ! don't set backreferences we use this to match the hostname we need
RewriteCond %{HTTP_HOST} ^(.*)$ [nc]

# For the Redirect itself:
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
link|improve this answer
This is breaking on me, redirecting to http:///. Could this be because I have a three-part domain name (draft.example.net to www.draft.example.net)? – TRiG Nov 8 '10 at 13:02
I think the backreference to %1 did not work correctly. You might try with the updated code snippet. – pacey Nov 8 '10 at 13:17
Thanks. I'll test that as soon as I can. (FTP server is down right now.) – TRiG Nov 10 '10 at 12:04
feedback

Look at this question on stackoverflow.

http://stackoverflow.com/questions/234723/generic-htaccess-redirect-www-to-non-www

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.