wordpress.htaccesshttp-redirectwildcard-subdomain

Redirect all subdomains to their respective normal domain in htaccess


I am using WordPress Multiste on CyberPanel. The child sites have their own mapped domains. I need all wildcard subdomains redirecting to their respective regular domain (without www)

For example, I have following sites. mainsite.com site2.com site3.com

Currently: anything.site2.com redirects to mainsite.com . Similarly, anything.site3.com redirects to mainsite.com

What I want is that: anything.site2.com redirects to site2.com , anything.site3.com redirects to site3.com , and so on.

What code should I add to .htaccess so that wildcard subdomains are redirected as mentioned?


Solution

  • Well, you want to match any requested host name inside any ".com domain", extract the base domain name from that and redirect any request to it:

    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^(?:.+)\.([^.]+\.com)$
    RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
    

    Update for the question you ask in the first comment to this answer:

    Sure, you could repeat the rule for all TLDs that are relevant, but that is only necessary if you want to use different rules. If you are not interested in the TLD at all, then just use a wildcard:

    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^(?:.+)\.([^.]+\.[^.]+)$
    RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
    

    If you want to accept just certain TLDs, then do that:

    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^(?:.+)\.([^.]+\.(?:com)|(?:org)|(?:info))$
    RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
    

    Or you can apply the rule just to specific domains:

    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^(?:.+)\.(exampleA.com)$ [OR]
    RewriteCond %{HTTP_HOST} ^(?:.+)\.(exampleB.org)$ [OR]
    RewriteCond %{HTTP_HOST} ^(?:.+)\.(exampleC.info)$
    RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]