I think both answers from @Paolo Stefan and @anubhava are valid (+1).
Please note: using RewriteMap will modify the apache configuration, and not just the .htaccess file. If you think a little about performance, you should essentially put everything in the .htaccess files into the <directory /same/filesystem/path/as/the/.htaccess/file/> directives and put AllowOverride None in the configuration Virtualhost You will of course get some speed by avoiding the I / O files and dynamic check-for-configuration-files settings for apache for each request (.htaccess files are bad, really). Therefore, a problem with RewriteMap is not available in .htaccess should not be a problem.
The theses of the two answers enable you to dynamically change file-based Authentication headers. Now, one important fact that you forgot to mention in your question is that the files are not directly accessible on the same server except PHP, and also that you do not want to run a script for each download.
With the current @anubhava solution, you will have an OS call for the file size at each access, and, of course, this script should be run on the file storage server.
One solution could be storage somewhere (dedicated database or key store)? file size index. You can feed this index after each load, you could manage some asynchronous tasks to maintain it. Then, on the Apache configuration of the file storage server, you will need to run a script check for file sizes. With RewriteMap, you have several options:
- use a very fast script with the
prg: keyword (written in C, Perl, nothing, you are not tied to PHP), querying this file size index in this data store or even fastdbd: to directly execute the SQL query in apache. But this means a request for each request, so you have other solutions. - use directly o the mapping file with the
txt: keyword txt: having for each file name the already calculated match size, more requests, just - even better, use the hashmap of this file with the dbm: `key.
With the last two parameters, the file size index is a text file or a hashed version of this text file. Apache caches the hash map and recalculates the cache on reboot or when the file modification time changes. Thus, you just need to recalculate this hash file after each boot to get a very fast file size check in RewriteRule, as shown in anubhava, but using
RewriteMap checkFileSize dbm:/path/to/filesize_precomputed_index.map
You can also try using mod_security on file servers and check the Content-Length header to add HTTP authentication. Check out this thread to start answering this question. But mod_security configuration is not an easy task.