Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use htaccess to force www. on multiple domains

Tags:

.htaccess

Basically I have a folder on my webserver that I assign to new domains whenever I buy them that only has an index.html and an images folder. It is basically just has my logo and says the domain is under construction and coming soon.

Normally when I want to force the www. prefix I use the following code:

rewritecond %{HTTP_HOST} ^domain.com [nc]
rewriterule ^(.*)$ http://www.domain.com/$1 [r=301,nc]

This works fine however I need to explicitly write out the name of the domain. I deal with a lot of domains so I need code that will do this without knowing the domain name. I gave it a go but honestly got no one where close.

like image 456
Andrew G. Johnson Avatar asked Mar 15 '09 20:03

Andrew G. Johnson


2 Answers

Try this:

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
like image 161
Gumbo Avatar answered Sep 29 '22 02:09

Gumbo


This would redirect "ftp.domain.com" to "www.ftp.domain.com". Probably not what you want.

This may require a bit of modification, but I decided to write my own so here ya go:

RewriteCond %{HTTP_HOST} !^%{SERVER_ADDR}$ [NC]
RewriteCond %{HTTP_HOST} !\.dev$ [NC]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ([^\.]+(\.[^\.0-9]{2,4}){1,2})$ [NC]
RewriteRule ^(.*)$ http://www.%1/$1 [R=permanent,L]

It should support one- and two-word TLDs, access by IP address, and DOMAIN.dev for developing locally. Works for domains with 4+ characters.

like image 42
Eso Avatar answered Sep 29 '22 03:09

Eso