There are some files (with unique names) in a directory structure like this:


At the moment, all of the domain directories are accessible as sub-directories of a master domain and clients can access the files using following URIs:


I'd like to modify Apache 2.4 configuration so that I will be able to access files without mentioning secondary domains in my URLs, for example:


And of course it's not desirable to do any redirect on client browsers (and event If I wanted, it would not be possible in this special case), I just need to directly server the files via second set of mentioned URLs.

Any ideas?

  • 2
    What would you wish to happen when the filenames in two different directories are the same? – Michael Hampton Dec 6 '17 at 21:13

You could create a RewriteMap that maps "unique" filenames to the domain it is stored under. You can then use a RewriteRule directive to lookup the domain from the requested "unique" filename and internally rewrite the request.

For example, in your server config, define the RewriteMap:

RewriteMap fn2domain "txt:/var/www/filename-to-domain-map.txt"

Then, in /var/www/filename-to-domain-map.txt you would include all your filename mappings:

# Filename to Domain map
unique_filename1 domain1
unique_filename2 domain2
unique_filename3 domain3

Now you can use mod_rewrite to reference this map in order to internally rewrite a request from /unique_filename2 to /domain2/unique_filename2 (for example).

RewriteEngine On
RewriteRule ^/([^/]+)$ /${fn2domain:$1}/$1 [L]

This assumes that "unique_filename" is exactly that; just a filename. No additional URL-path.

You could make the lookup more efficient by using a dbm: DBM Hash File (or fastdbd: SQL Query?) instead of a plain text file, if you have many "filenames".


Alternatively, you could perform filesystem checks for the existence of "unique_filename" in each domain subdirectory. The first match wins. This might be OK if you only have 2 or 3 domain subdirectories, but if you have many then this might become a performance problem as filesystem checks are relatively expensive. For example, again using mod_rewrite:

RewriteEngine On

# Is it in domain1? Then rewrite to domain1 subdirectory
RewriteRule %{DOCUMENT_ROOT}/domain1/$1 -f
RewriteRule ^/([^/]+)$ /domain1/$1 [L]

# Is it in domain2? Then rewrite to domain2 subdirectory
RewriteRule %{DOCUMENT_ROOT}/domain2/$1 -f
RewriteRule ^/([^/]+)$ /domain2/$1 [L]

# Is it in domain3? Then rewrite to domain3 subdirectory
RewriteRule %{DOCUMENT_ROOT}/domain3/$1 -f
RewriteRule ^/([^/]+)$ /domain3/$1 [L]

# Repeat for each domain...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.