0

I use WordPress and would like to redirect all non-existing subdomains (or all subdomains) to the main domain.

Examples of urls to be redirected:

  • subdomains.example.com
  • subdomains.example.com/xxx
  • subdomains.example.com/xxx.html
  • subdomains.example.com/t/xxx.php

TO

www.example.com

This is my default WordPress .htaccces of the main domain (I am editing this). Any folders or files for non-existing subdomains do not exist.

# BEGIN WordPress

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    </IfModule>

# END WordPress
7
  • Check this answer: webmasters.stackexchange.com/a/102851/73879
    – Fayaz
    Feb 27, 2017 at 16:28
  • this is useless @Fayaz
    – user105919
    Feb 27, 2017 at 16:32
  • It's not useless, you simply failed to understand it. if you use not operator ! like RewriteCond %{HTTP_HOST} !^example\.com$, it'll take care of all the subdomains. Anyways, I would answer your question to the point, but this question is off topic here.
    – Fayaz
    Feb 27, 2017 at 16:36
  • Also, before it can be used, you must point all subdomains with *.example.com to point to your main domain from your DNS setting.
    – Fayaz
    Feb 27, 2017 at 16:38
  • so this is not the best solution if I need to point every domain in DNS settings. I would be grateful if you could post your exact htacces code with the dns remark. It will help thousands of wordpress users !
    – user105919
    Feb 27, 2017 at 16:44

1 Answer 1

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.