Using mod-rewrite to conditionally select existing file in a subdirectory based on Host header?

Posted by Kevin Hakanson on Stack Overflow See other posts from Stack Overflow or by Kevin Hakanson
Published on 2010-04-20T19:33:50Z Indexed on 2010/04/20 19:43 UTC
Read the original article Hit count: 238

Filed under:
|
|

I'm working through a problem where I want to select a different static content file based on the incoming Host header. The simple example is a mapping from URLs to files like this:

  • www.example.com/images/logo.gif -> \images\logo.gif
  • skin2.example.com/images/logo.gif -> \images\skin2\logo.gif
  • skin3.example.com/images/logo.gif -> \images\skin3logo.gif

I have this working with the following RewriteRules, but I don't like how I have to repeat myself so much. Each host has the same set of rules, and each RewriteCond and RewriteRule has the same path. I'd like to use the RewriteMap, but I don't know how to use it to map the %{HTTP_HOST} to the path.

<VirtualHost *:80>
    DocumentRoot "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs"
    ServerName www.example.com
    ServerAlias skin2.example.com
    ServerAlias skin3.example.com

    RewriteEngine On

    RewriteCond %{HTTP_HOST} skin2.example.com
    RewriteCond %{DOCUMENT_ROOT}$1/skin2/$2 -f
    RewriteRule ^(.*)/(.*) $1/skin2/$2 [L]

    RewriteCond %{HTTP_HOST} skin3.example.com
    RewriteCond %{DOCUMENT_ROOT}$1/skin3/$2 -f
    RewriteRule ^(.*)/(.*) $1/skin3/$2 [L]
</VirtualHost>

The concept behind the rules is if the same filename exists in a subdirectory for that host, use it instead of the direct targeted file. This uses host based subdirectories at the lowest level, and not a top level subdirectory to separate content.

© Stack Overflow or respective owner

Related posts about mod-rewrite

Related posts about virtualhost