I know this is an old topic and there have been many threads already. I've resolved anything.example.com to example.com in DNS settings and set up virtual hosts in http.conf:
<VirtualHost 1.1.1.1>
ServerAlias example.com *.example.com
ServerName www.example.com
DocumentRoot /home/example.com/public_html
</VirtualHost> Now the difficult part is .htaccess. I use the following codes:
##################################################
RewriteEngine On
# Rewrite <subdomain>.example.com/<path> to example.com/<subdomain>/<path>
#
# Skip rewrite if no hostname or if subdomain is www
RewriteCond %{HTTP_HOST}.
RewriteCond %{HTTP_HOST}!^www\. [NC]
# Extract (required) subdomain (%1), and first path element (%3), discard port number if present (%2)
RewriteCond %{HTTP_HOST}<>%{REQUEST_URI}^([^.]+)\.example\.com(:80)?<>/([^/]*) [NC]
# Rewrite only when subdomain not equal to first path element (prevents mod_rewrite recursion)
RewriteCond %1<>%3!^(.*)<>\1$[NC]
# Rewrite to /subdomain/path
RewriteRule ^(.*)/%1/$1[R] <---?
##################################################
Everytime I use [L] in the last line, it fails with a 500 error. While if I use [R], it works but the problem is when
a request of http ://anything.example.com will be redirected to http ://example.com/anything/ instead of going there secretly.
Thanks in advance.