This is a wildcard based solution, so it sould work for any number of subdomains.
This will redirect domain.com/foo/bar
to foo.domain.com/bar
:
RewriteCond %{HTTP_HOST} ^domain.com$ [NC]
RewriteRule ([^/]+)(/.*|$) $1.domain.com/$2 [R=302]
This will handle (internal rewrite) the virtual hosts:
RewriteCond %{HTTP_HOST} ^(.*).domain.com$ [NC]
RewriteRule (.*) %1/$1 [L]
You might consider using 301 (permanent redirect) instead of the 302.
I strongly suggest you have a VirtualHost
for your main site domain.com or www.domain.com and a separate one for handling the virtual subdomains.
For only a certain subdomain:
RewriteCond %{HTTP_HOST} ^domain.com$ [NC]
RewriteRule (subdomain)(/.*|$) $1.domain.com/$2 [R=302,L]
RewriteCond %{HTTP_HOST} ^(subdomain).domain.com$ [NC]
RewriteRule (.*) %1/$1 [L]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…