在nginx中添加自定义HTTP头X-Accel-Redirect

9
我正在使用nginx和X-Accel-Redirect来提供受限制的下载服务。为了在客户端应用程序中验证我的下载,我尝试将校验和发送到非标准HTTP头Content-MD5中,并将其发送到X-Accel-Redirect请求中。但是这种方法不起作用。

以下是用于重定向的rails代码片段:

headers['X-Accel-Redirect'] = '/download_public/uploads/stories/' + params[:story_id] +'/' + params[:story_id] + '.zip'
            headers['X-Accel-Expires'] = 'max'
            checksum = Digest::MD5.file(Rails.root.dirname.to_s+'/public/uploads/stories/' + params[:story_id] +'/' + params[:story_id] + '.zip').hexdigest
            headers['Content-MD5'] = checksum
            request.session_options[:skip] = true
            render :nothing => true, :content_type => MIME::Types.type_for('.zip').first.content_type

这是关于nginx的部分。
location /download_public { 
 internal;
 proxy_pass_header Content-MD5;
 add_header Cache-Control "public, max-age=315360000";
 add_header Content-Disposition "inline"; 
 alias /var/www/sss/public; 
}

显然这个方法不起作用。我无法在响应中获取Content-MD5头信息。有没有办法从rails中传递我的Content-MD5头信息?

我知道有一些完全在nginx中完成的方法,比如使用perl或lua编译nginx,并轻松地动态计算MD5。但我不想这样做。

非常感谢任何帮助。


尝试使用 add_header Content-MD5 $upstream_content_md5; - Alexey Ten
@AlexeyTen,我遇到了这个错误 nginx: [emerg] unknown "upstream_content_md5" variable - RameshVel
1
糟糕,这是$upstream_http_content_md5。请参阅http://nginx.org/r/$upstream_http_。 - Alexey Ten
@AlexeyTen,它有效了.. :) 请将其添加为答案,我会接受它。 - RameshVel
2个回答

21

使用add_header Content-MD5 $upstream_http_content_md5;

由于X-Accel-Redirect会引起内部重定向,nginx不会发送返回的头部信息,但是它们会保存在$upstream_http_...变量中。因此,您可以使用它们。


同样的问题,但涉及到AWS S3重定向。您能否看一下这里的问题:https://dev59.com/ubLos4cB2Jgan1zn7kgE 。非常感谢您的任何帮助。 - RameshVel
如果我在“internal”位置内执行proxy_pass,则$upstream_..变量会变为空。如何解决这个问题? - urmurmur
@urmurmur 提出新问题 - Alexey Ten
nginx will not send returned headers - seems Content-Type is an exception, that header will be forwarded even without add_header - hanshenrik

5

我尝试了被接受的答案,但对我没有用。但这个方法有效:

 set $authorization "$upstream_http_authorization";
 proxy_set_header Authorization $authorization; # Pass on secret from back end

(从此文章 https://clubhouse.io/developer-how-to/how-to-use-internal-redirects-in-nginx/ 复制粘贴)

有趣的是提取变量很重要。这对我没有用:

 proxy_set_header Authorization "$upstream_http_authorization";

这个答案被低估了。我可以确认,如果没有变量,它是不起作用的。谢谢。 - binwiederhier
是的,确实很有趣,它会以这种方式表现。我已经阅读并反复阅读了nginx文档,但我完全无法理解为什么它会这样做。有答案的人,请说出来!:-D - Neilski
对我而言,只有这个有效:more_set_headers "Content-Security-Policy: $upstream_http_content_security_policy"; (我需要为通过X-Accel-Redirect提供的文件设置CSP头。) - panzi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接