Redirect all subdomains to root domain

The following .htaccess will only work if the subdomain is assigned in your DNS setting using either a single DNS record or a wildcard DNS record. If your DNS setting doesn’t have that record, request to your subdomain will not reach to your server. So the .htaccess will not work.

If you don’t know how to edit DNS record, then ask your web hosting provider. Then use the following .htaccess CODE:

# BEGIN WordPress
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    # the following three lines will work for all subdomains
    RewriteCond %{HTTP_HOST} !^example\.com$ [NC]
    RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
    RewriteRule . "http://www.example.com/" [R=301,L]

    # the following two lines will redirect non-www to www version of the domain
    RewriteCond %{HTTP_HOST} ^example\.com$
    RewriteRule ^(.*)$ "http://www.example.com/$1" [R=301,L]

    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    </IfModule>
# END WordPress