我想允许用户从远程存储下载文件,但我想先通过我的 rails 应用程序验证请求。我想在 rails 验证请求后将远程文件的代理移交给 nginx,以释放 ruby/rails 线程。
我有一个名为 proxy_download.conf 的 nginx conf 文件:
# Proxy download
location ~* ^/internal_redirect/(.*?)/(.*) {
# Do not allow people to mess with this location directly
# Only internal redirects are allowed
internal;
# Location-specific logging
access_log logs/internal_redirect.access.log combined;
error_log logs/internal_redirect.error.log warn;
# Extract download url from the request
set $download_uri $2;
set $download_host $1;
# Compose download url
set $download_url http://$download_host/$download_uri;
# Set download request headers
proxy_set_header Host $download_host;
proxy_set_header Authorization '';
# The next two lines could be used if your storage
# backend does not support Content-Disposition
# headers used to specify file name browsers use
# when save content to the disk
proxy_hide_header Content-Disposition;
add_header Content-Disposition 'attachment; filename="$args"';
# Do not touch local disks when proxying
# content to clients
proxy_max_temp_file_size 0;
# Download the file and send it to client
proxy_pass $download_url;
}
我将其导入到主 nginx 配置中,如下所示:
include $ROOT/TO/APP/nginx.conf.d/proxy_download.conf;
通过此设置,应用程序可以顺利部署并正常运行。
这些是启动下载请求的控制器方法:
def x_accel_url(url, file_name = nil)
uri = "/internal_redirect/#{url.gsub('http://', '').gsub('https://', '')}"
uri << "?#{file_name}" if file_name
return uri
end
def download
if auth_is_ok # do some auth logic here
headers['X-Accel-Redirect'] = x_accel_url('http://domain.com/file.ext')
render :nothing => true
end
end
当通过浏览器访问此控制器方法时,我得到了著名的 nginx 错误:
502 Bad Gateway
我的设置有什么问题?谢谢!