Monday, February 21, 2011

Need help with Apache's mod_rewrite to fetch file based on url

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...

The subdomains are numerous and are added and removed often, so I'm trying to find a solution that works for all of them.

From stackoverflow
  • In sub.domain's httpd config:

    RewriteCond %{HTTP_HOST} ([^\.]+).domain
    RewriteRule ^/file.bin$ http://domain/hosted/%1/file.bin
    
    Cypher : Hrm, getting close. How could I make the "sub" dynamic based on whatever the subdomain is in the initial url?
  • 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]
    

0 comments:

Post a Comment