Forum Moderators: phranque
RewriteEngine On
RewriteCond %{HTTP_HOST}!^$
RewriteCond %{HTTP_HOST}!^(www\.)?domain\.com$ [NC]
RewriteCond %{HTTP_HOST}<->%{REQUEST_URI} ^(www\.)?([^.]+).*<->/([^/]+) [NC]
RewriteCond %2<->%3!^(.*)<->\1$ [NC]
RewriteRule ^(.+) /%2/$1 [L]
Welcome to WebmasterWorld!
If you want to access your files by subdomains, then link to them as subdomains on your pages. Use the code you found to receive those subdomain request URLs, and convert them to subdirectory file-paths in order to retrieve the correct content.
I highlighted the critical words above: The URL shows a subdomain, but the files are stored in the filesystem under a subdirectory. Mod_rewrite executes after an HTTP request is received from the client, but before any content-handlers are activated or any scripts are invoked. In this case, mod_rewrite receives the requested URL and converts it into a filesystem path. Since subdomains don't exist in a filesystem, mod_rewrite can't rewrite subdirectories to subdomains.
So, the usual approach is this:
A simple demonstration for use in the Web-root .htaccess would be:
# Rewrite foo subdomain requests to foo subdirectory
RewriteCond %{HTTP_HOST} ^foo\.example\.com
RewriteCond %{REQUEST_URI} !^/foo/
RewriteRule (.*) /foo/$1 [L]
#
# Prevent direct client access to foo subdirectory
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /foo [NC]
RewriteRule ^foo(.+) http://foo.example.com$1 [R=301,L]
Jim