Lore

Redirecting a subsubdomain

On a recent project that uses a wildcard domain I needed to catch subsubdomains (multiple subdomains) and redirect back to the subdomain.

The specific issue was www.subdomain.domain.com needed to redirect to just subdomain.domain.com. There are plenty of examples to remove www explicitly but since this is a wild card it could be any.crazy.thing.subdomain.domain.com.

Here’s the solution I added to the Apache vhost:
RewriteEngine On
RewriteCond %{HTTP_HOST} .+\.(.+)\.example\.com$ [NC]
RewriteRule ^(.*)$ https://%1.example.com/$1 [R=301,NC,L]

In the RewriteCond it matches anything up front then captures the subdomain in the parenthesis. Similar to $1 capturing the first match in a RewriteRule, %1 captures the first match in the RewriteCond. The RewriteRule captures everything and puts the URL back together nicely.