什么是X-accel?
Nginx反向代理服务器会根据服务器返回的header信息实现内部地址重定向,这依赖于X-accel。针对费时的请求,它能够使web服务快速地做一些额外工作(权限验证、日志记录等),然后直接将请求移交给Ngnix处理。这种技术通常被称为X-Sendfile。
它的工作方式比较简单,服务器发送一个带 x-accel-redirect的header,ngnix解析出x-accel-redirect中的uri跟配置文件中location进行匹配,然后将匹配之后的路径作为请求,并删除x-accel-redirect头。
# Will serve /var/www/files/myfile.tar.gz
# When passed URI /protected_files/myfile.tar.gz
location /protected_files {
# internal表示路径只能内部访问,文件存储路径对浏览器不可见
internal;
alias /var/www/files;
}
# Will serve /var/www/protected_files/myfile.tar.gz
# When passed URI /protected_files/myfile.tar.gz
location /protected_files {
internal;
root /var/www;
}
rails文件下载
在rails中,通常会使用send_file进行数据流的传输。由于rails是一种单线程架构,资源是非常宝贵的,在处理大文件下载时,服务长时间被一个client占用,会导致其他的client被阻塞,这种体验是极其不好的。
这种情境下,x-accel-redirect就显现出威力了。我们将文件下载重定向nginx,释放slow client直接对web服务的请求。
1、取消config/environments/production.rb文件如下配置的注释
# for nginx
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
2、配置nginx.conf location路径
location /dl_file/{
internal;
alias /path/to/download-file/;
}
3、代码实现
begin
if Rails.env = 'production'
return head(
'X-Accel-Redirect' => "/dl_flie/#{filename}",
'Content-Length' => filesize,
'Content-Type' => "application/zip",
'Content-Disposition' => "attachment; filename=\"#{filename}\""
)
else
send_file(store_dir + filename, filename: filename, type: "application/zip")
end
rescue Exception => e
not_found
ensure
logger.info response.headers
end