Wildcard subdomains redirected to www with htaccess

There seem to be a million posts on StackOverflow on this topic, but none seem to be exactly what I’m after.

Basically, I’m trying to redirect all random non-existent subdomains to the “www” version of a URL.

Read More

For example, if someone types “whatever.mydomain.com” in the address bar, this should redirect to “www.mydomain.com”. This is also a WordPress driven site, so I’m wondering if WP’s existing rewrite rules are causing the redirect loops that have happened with many of the pieces of code I’ve tried.

It should also be noted that currently the site redirects from the non-www version to the www version, but I can’t for the life of me find where that is occurring. It’s not in the .htaccess file, and I don’t know where else to look for that.

Thanks.

Related posts

Leave a Reply

1 comment

  1. Try adding this at the top of your .htaccess file in the root folder of mydomain.com

    RewriteEngine on
    RewriteBase /
    
    #for all requests on mydomain.com
    RewriteCond %{HTTP_HOST} mydomain.com$ [NC]
    #if they are not for the www.mydomain.com
    RewriteCond %{HTTP_HOST} !^www.mydomain.com$ [NC]
    #301 redirect to www.mydomain.com
    RewriteRule (.*) http://www.mydomain.com/$1 [R=301,L]