Search code examples
regex.htaccessurlmod-rewritewildcard-subdomain

Redirect or rewrite any subdomain to www leaving the rest of URL as it is


I have:

subdomainaaa.mydomain.com
subdomainaaa.mydomain.com/anything/whatever
subdomainbbb.mydomain.com
subdomainbbb.mydomain.com/anything/whatever
...
...
anysubdomain.mydomain.com ...

Practically wild card subdomain.

And I need rewrite rule to make it all:

www.mydoamin.com/and_whatever_goes_afterwords

Basically, how to redirect zillion subdomains to www, leaving anything that goes after .com/ as it is.

I must do some sort of permanent redirection because I can't lose old links, just to redirect them to new ones with www instead of subdomains

Please, I was looking all over the internet for this, and I get only chunks of regex which I don't know how to put together, and whatever I mix in my .htaccess file - I get server error. Or, I manage to redirect anything just to the homepage www.mydomain.com. I hope I was clear. I am a regex newbie (wannabe), so, please give me the whole chunk to put in .htaccess. Or, if you think I am doing something wrong - give me suggestion how to accomplish my goal. Thanks a lot guys!!


Solution

  • You may use this rule in your site root .htaccess:

    RewriteEngine On
    
    # add www and keep same URI
    RewriteCond %{HTTP_HOST} ^(?!www\.)[^.]+\.(mydomain\.com)$ [NC]
    RewriteRule ^ http://www.%1%{REQUEST_URI} [R=301,L,NE]