Using apache mod_rewrite to support multiple subdomains in the same virtual host

Here’s a trick for redirecting multiple subdomains like sub.domain.tld to www.domain.tld/sub.

ServerAdmin webmaster@servername.tld
DocumentRoot /home/www/domain.tld/html
DirectoryIndex index.php index.htm index.html
ServerName domain.tld
ServerAlias www.domain.tld
ServerAlias subdomain1.domain.tld
ServerAlias subdomain2.domain.tld
RewriteEngine On
RewriteCond %{HTTP_HOST} ^subdomain1\.domain\.tld$ [NC]
RewriteRule ^(.*)$ http://www.domain.tld/subdomain1$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^subdomain2\.domain\.tld$ [NC]
RewriteRule ^(.*)$ http://www.domain.tld/subdomain2$1 [R=301,L]

This comes in handy if you want to support multiple subdomains in the same apache virtual host. All the subdomain pages can then be stored under DocumentRoot without creating different virtual hosts.