How do I use mod_rewrite to alter which file is fetched based on the URL's sub-domain?
So say I have a URL being requested:
sub.domain/file.bin
and I wanted this file to be fetched:
domain/hosted/sub/file.bin
How would I structure the rewrite directives? I've been working on this for days, and it just gives me a headache...
开发者_C百科The sub-domains are numerous and are added and removed often, so I'm trying to find a solution that works for all of them.
In sub.domain's httpd config:
RewriteCond %{HTTP_HOST} ([^\.]+).domain
RewriteRule ^/file.bin$ http://domain/hosted/%1/file.bin
Assuming the home directory for www.domain.com
is domain/
and that - given any subdomain sub.domain.com
- you want the files for the home directories for that sub-domain to be in domain/hosted/sub/
Try something like this:
RewriteEngine on
// If the host is just mydomain.com, do nothing more
// this is to prevent some recursion problems I've read of...
RewriteCond %{HTTP_HOST} ^(www\.)?mydomain\.com$ [NC]
RewriteRule ^.*$ - [L]
// Otherwise strip off everything before mydomain
// And add it to the start of the request
RewriteCond %{HTTP_HOST} ^(.*?)\.(www\.)?mydomain\.com$ [NC]
RewriteRule ^.*$ %1%{REQUEST_URI} [QSA]
// Then prefix with 'hosted'
RewriteRule ^(.*)$ hosted/$1 [QSA,L]
You may also need a wildcard entry in your DNS or something... but I will admit DNS and htaccess mod rewrite are some of my weaker points. See also http://www.webmasterworld.com/forum92/138.htm
Try this rule:
RewriteCond %{HTTP_HOST} ^([^/.]+)\.example\.com$
RewriteCond %1 !=www
RewriteRule !^hosted/ hosted/%1%{REQUEST_URI} [L]
精彩评论