Apache: mapping multiple directories to the same location

apache-2.2configurationstatic-files

I would like to map multiple directories to the same location with Apache, expecting a behaviour similar to this: suppose that the /static location is to be backed by directories /srv/static1 and /srv/static2. Then if /static/image.png is requested, I would like Apache to check for files /srv/static1/image.png and /srv/static2/image.png, in that order. First file found is returned; if neither is found, classical error 404 is sent back.

Of course a solution is to use a script to make a directory of symlinks that point to the right location and use that one, for example in an Alias directive. I wonder if there is a more direct way that doesn't require me to deploy additional machinery.

Thanks!

Best Answer

This is easily done using mod_rewrite. You can set it up to have a condition that if the file doesn't exist in the first directory, it should look in the second one instead, and so on.

Here's a short sample configuration; for further information please see the canonical mod_rewrite question and apache's mod_rewrite documentation.

RewriteEngine on

# first try to find it in dir1/...
# ...and if found stop and be happy:
RewriteCond %{DOCUMENT_ROOT}/dir1/%{REQUEST_URI} -f
RewriteRule ^(.+) %{DOCUMENT_ROOT}/dir1/$1 [L]

# second try to find it in dir2/...
# ...and if found stop and be happy:
RewriteCond %{DOCUMENT_ROOT}/dir2/%{REQUEST_URI} -f
RewriteRule ^(.+) %{DOCUMENT_ROOT}/dir2/$1 [L]

# else go on for other Alias or ScriptAlias directives,
# etc.
RewriteRule ^ - [PT]