views:

422

answers:

2

Hello guys,

I'm trying to figure it out how to set up an .htaccess set of rules that would force the presence of the "www" in front of the domain if it is not initially specified, but at the same time, it will not have any effect if the an subdomain is pressent; all this without hard coding any domain name so that the script is portable around different servers and configurations.

Thank you in advance for your support,

Constantin TOVISI

EDIT:

I'm sorry I was not able to get this explained right in the fist place. So what I need is as follows:

http://example.com -> redirects to http://www.example.com

http://www.example.com -> does not redirect

http://subdomain.example.com -> does not redirect

+4  A: 

This mod_rewrite rule should do it for second level domains:

RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Gumbo
yes, this partly works, but it does not cover the subdomain part; for instance, if the you access the http://subdomain.example.com you get redirected to http://www.subdomain.example.com, which you should not.
titel
I guess there is an issue with SO, the second URL I wrote above was http:// www .subdomain.example.com (with www)
titel
@titel: I got what you wanted to say. It should work now for any second level domains.
Gumbo
@Gumbo - I'm afraid I was still unable to make myself understood; please read the edit above
titel
just added this line as the first rule of the rewrite and everything seems to work out fine now RewriteCond %{HTTP_HOST} !^www\.[a-z0-9]+\.[a-z]{2,6} [NC]
titel
A: 
RewriteCond %{HTTP_HOST} ^example\.org
RewriteRule ^ http://www.example.org%{REQUEST_URI} [L,R=301]

This will not redirect subdomains like mail.example.org

Sander Marechal