In Apache .htaccess, I have below block to force download.
<If "%{QUERY_STRING} =~ /fileName=/">
ForceType application/octet-stream
Header set "Content-disposition" "attachment; filename=download.doc"
</If>
This works fine. Now I need to make the filename be the value of query string key "fileName".
I know how to do this in Nginx. Below is the code.
if ($arg_fileName) {
set $fname $arg_fileName;
add_header Content-Disposition 'attachment; filename="$fname"';
}
How to do this in Apache .htaccess?
You could do something like this with the help of mod_rewrite:
([^&]+)- Note, however, that you might want to restrict the regex used to match thefileNameparameter value, since not everything is necessarily permitted in the filename argument of the HTTP response header. This can vary by browser and modern browsers do support more. Note also that the value grabbed from theQUERY_STRINGis already URL-encoded. So, maybe something like([\w.-]+)would be sufficient instead to match justa-z,A-Z,0-9,_,.and-?The
env=FILENAMEargument results in the header only being set when the FILENAME env var exists, so this negates the need for the<If>expression.This isn't strictly necessary to trigger a download, it is the
Content-Disposition: attachmentheader that does this in any remotely modern browser. In fact, it is not necessarily recommended to send theapplication/octet-streammime-type for all responses. You should be sending the correctContent-Typeheader for the resource being sent.