[英]In Apache .htaccess, set Header set Content-disposition, how to pass the filename from QUERY_STRING value
In Apache .htaccess, I have below block to force download.在 Apache .htaccess 中,我有以下块来强制下载。
<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".
现在我需要使文件名成为查询字符串键“fileName”的值。
I know how to do this in Nginx.我知道如何在 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?如何在 Apache .htaccess 中做到这一点?
Thank you.谢谢你。
You could do something like this with the help of mod_rewrite:你可以在 mod_rewrite 的帮助下做这样的事情:
RewriteEngine On
# Save value of fileName URL param in environment variable FILENAME
RewriteCond %{QUERY_STRING} (?:^|&)fileName=([^&]+)
RewriteRule ^ - [E=FILENAME:%1]
# Conditionally set header only if FILENAME is set and use this in the header itself
Header set "Content-Disposition" "attachment; filename=\"%{FILENAME}e\"" env=FILENAME
([^&]+)
- Note, however, that you might want to restrict the regex used to match the fileName
parameter value , since not everything is necessarily permitted in the filename argument of the HTTP response header. ([^&]+)
- 但是请注意,您可能希望限制用于匹配fileName
参数值的正则表达式,因为在 HTTP 响应标头的filename参数中不一定允许所有内容。 This can vary by browser and modern browsers do support more .这可能因浏览器而异,现代浏览器确实支持更多。 Note also that the value grabbed from the
QUERY_STRING
is already URL-encoded.另请注意,从
QUERY_STRING
值已经是 URL 编码的。 So, maybe something like ([\\w.-]+)
would be sufficient instead to match just az
, AZ
, 0-9
, _
, .
所以,也许像
([\\w.-]+)
这样的东西就足以匹配az
, AZ
, 0-9
, _
, .
and -
?和
-
?
The env=FILENAME
argument results in the header only being set when the FILENAME env var exists, so this negates the need for the <If>
expression. env=FILENAME
参数导致仅当 FILENAME env var 存在时才设置标头,因此这不需要<If>
表达式。
ForceType application/octet-stream
This isn't strictly necessary to trigger a download , it is the Content-Disposition: attachment
header that does this in any remotely modern browser.这并不是触发下载所必需的,而是
Content-Disposition: attachment
标头在任何远程现代浏览器中执行此操作。 In fact, it is not necessarily recommended to send the application/octet-stream
mime-type for all responses.事实上,不一定建议为所有响应发送
application/octet-stream
mime-type。 You should be sending the correct Content-Type
header for the resource being sent.您应该为正在发送的资源发送正确的
Content-Type
标头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.