Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to redirect www subdomain to non-www when domain is redirected to www

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! :)

like image 409
hello Avatar asked Feb 24 '14 10:02

hello


People also ask

Should you redirect www to non-www?

For example, if you've chosen to use non-www URLs as the canonical type, you should redirect all www URLs to their equivalent URL without the www. Example: A server receives a request for http://www.example.org/whaddup (when the canonical domain is example.org)

Can you put www in front of a subdomain?

Generally, the www prefix is not used when using subdomains. If you want to use the prefix with your subdomain, you can make a vhost file and add this behavior as part of your domain configuration.

Is www default subdomain?

remember, the www is just a subdomain. Also no www is a commonplace these days, so maybe make the www.foo.com redirect to foo.com. It's even easier to type "google <Ctrl-Enter>", which adds both "www." and ".com" in most(?) browsers.


2 Answers

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]
like image 107
anubhava Avatar answered Oct 27 '22 17:10

anubhava


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]
like image 45
Vahid Amiri Avatar answered Oct 27 '22 17:10

Vahid Amiri