nginx X-Accel-Redirect实现文件下载权限控制及rails devise实现

问题1:Nginx的X-Accel-Redirect?

答:

对文件下载的权限进行精确控制在很多地方都需要,例如有偿的下载服务,网络硬盘,个人相册,防止本站内容被外站盗链。

假设下载文件的路径在/path/to/files,比如有/path/to/files/test1.txt,可以在nginx里配置

location /down {
#这个路径只能在nginx内部访问
    internal;
    alias /path/to/files;
}

 关键字 internal 指明了那些目录需要通过X-Accel-Redirect头与后台脚本进行内部转向。

问题2: rails利用Nginx的X-Accel-Redirect头实现下载控制?

答:

在nginx的配置文件中添加

location /downloads {
    internal;
    alias /path/to/files; #实际存放下载文件的目录
}

在rails的controller中添加

def download
  if authenticated? #进行验证...
    #Set the X-Accel-Redirect header with the path relative to the /downloads location in nginx
    response.headers['X-Accel-Redirect'] = '/downloads/myfile.zip'
    #Set the Content-Type header as nginx won't change it and Rails will send text/html
    response.headers['Content-Type'] = 'application/octet-stream'
    #If you want to force download, set the Content-Disposition header (which nginx won't change)
    response.headers['Content-Disposition'] = 'attachment; filename=myfile.zip'
    #Make sure we don't render anything
    render :nothing => true
  end
end

并且在config/routes.rb路由中添加该controller的路径

#得到要下载的文件名

filename = @params["filename"]

问题3:rails的devise安装及使用http-basic?

答:

devise是提供了登录和验证授权的解决方案

在rails3中安装devise

在Gemfile中添加

gem 'devise'

bundle install

使用

接下来是通过generate安装devise相关代码

rails generate devise:install

rails generate devise user

rails generate devise:views

rake routes 查看路由

在controllers里的applicationController.rb中添加

before_filter :authenticate_user!

配置devise的HTTP Basic Auth

config/initializers/devise.rb设置

config.http_authenticatable = true

重启服务

curl -u [email protected]:password http://127.0.0.1/download

curl http://xx%40xx.com:[email protected]/download

ps:

rails plugin X-Accel-Redirect

@asc%40

http://presentations.royvandewater.com/authentication-with-devise.html

varnish -> cache

proxy_pass -> config

猜你喜欢

转载自zhou-xingbo.iteye.com/blog/961132