How to add a custom redirect rule for subdomains?

It’s better not to use these sort of subdomain redirect rules within WordPress:

  1. WordPress may not load properly when you access it using the wrong domain name or sub-domain, as a typical WordPress installation is set to run for a particular domain or subdomain.

  2. Even if you are able to make it work, before every redirect WordPress will first load itself and then do the redirect and then load again when the redirected URL reaches the server. That’s a slow process.

Instead do it in .htaccess. Like the following:

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

# custom rules for subdomain matching
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com$ [NC]
RewriteRule . http://example.com/%1 [R=301,L]

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

This will redirect all sub.example.com to example.com/sub.

Note: The above CODE will also redirect www.example.com to example.com/www. If you don’t want that, then modify the above # custom rules for subdomain matching section to the following:

# to redirect www.example.com/* to example.com/*
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^(.*)$ "http://example.com/$1" [R=301,L]
# custom rules for subdomain matching
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com$ [NC]
RewriteRule . http://example.com/%1 [R=301,L]

Read this doc. to learn more about apache mod_rewrite.

Also, make sure mod_rewrite is enabled for .htaccess in your server.