7

My primary domain is currently permanently redirected to www.mydomain.com (non-www to www redirection), with .htaccess as follows:

RewriteCond %{HTTP_HOST} ^mydomain.com$
RewriteRule ^/?$ "http\:\/\/www\.mydomain\.com\/" [R=301,L]

RewriteCond %{HTTP_REFERER} !^http://mydomain.com/.*$      [NC]
RewriteCond %{HTTP_REFERER} !^http://mydomain.com$      [NC]
RewriteCond %{HTTP_REFERER} !^http://www.mydomain.com/.*$      [NC]
RewriteCond %{HTTP_REFERER} !^http://www.mydomain.com$      [NC]

I would like to know how all subdomains that I'll be creating, ex. blog.mydomain.com, will be redirected to non-www, ex. blog.mydomain.com, and not www.blog.mydomain.com. Every time I create a subdomain and enter the non-www URL to the browser, it prompts a redirect loop.

Hope you can help! Thanks! :)

hello
  • 351
  • 3
  • 4
  • 16
  • Possible duplicate of [htaccess add www if not subdomain, if subdomain remove www](https://stackoverflow.com/questions/35285074/htaccess-add-www-if-not-subdomain-if-subdomain-remove-www) – Will Craig Nov 12 '17 at 02:03

2 Answers2

21

Keep this one rule for all the sub-domains:

# rule for forcing www on main domain
RewriteCond %{HTTP_HOST} ^mydomain\.com$ [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# rule for removing www on sub domains
RewriteCond %{HTTP_HOST} ^www\.([^.]+\.mydomain\.com)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Can we make http part dynamic so that if site changes to https then it should be automatic? – RN Kushwaha Feb 13 '16 at 20:08
  • This is not working if anyone adds `https://` before `www.sub.domain.com` – MrinmoyMk May 20 '20 at 11:18
  • It is definitely a working rule and it has nothing to do with `https` – anubhava May 20 '20 at 11:35
  • Suppose I have my subdomain xyz.abc.com and now if someone browse to www.xyz.abc.com then it perfectly redirects to xyz.abc.com but if anyone adds https:// infront of www.xyz.abc.com then it is not able to redirect to without www – MrinmoyMk May 20 '20 at 12:03
  • @MrinmoyMk: Can you post a new question for this and I will post an answer there. – anubhava May 20 '20 at 13:52
  • this works fine for main domain and it redirect `mydomain.com` to `https://www.` as I want but it doesn't redirect `sub.mydomain.com` to `https://sub.` – Cem Dec 30 '22 at 17:29
  • @Cem: This answer is not for `http -> https`. This is for removal of `www` for subdomains and adding `www` for main domain. – anubhava Dec 31 '22 at 05:49
2

This one supports http + https in one line:

# Redirect www subdomain to non-www 
RewriteCond %{HTTP_HOST} ^www\.([^.]+\.yourdomain\.com)$ [NC]
RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [R=301,L]
Vahid Amiri
  • 10,769
  • 13
  • 68
  • 113