【问题标题】:Content-Length Header missing from Nginx-backed Rails appNginx 支持的 Rails 应用程序缺少 Content-Length 标头
【发布时间】:2014-05-08 17:06:07
【问题描述】:

我有一个向注册用户提供大型静态文件的 Rails 应用程序。我可以按照这里的优秀指南来实现它:Protected downloads with nginx, Rails 3.0, and #send_file。下载和其他一切都运行良好,但只有这个问题 - Content-Length 标头未发送。

小文件没问题,但下载大文件时会让人很沮丧,因为下载管理器和浏览器不会显示任何进度。我怎样才能解决这个问题?我是否必须在我的 nginx 配置中添加一些东西,或者我是否必须将一些其他选项传递给我的 rails 控制器中的 send_file 方法?我在网上搜索了很长时间,但没有成功。请帮忙!谢谢!

这是我的nginx.conf

upstream unicorn {
  server unix:/tmp/unicorn.awesomeapp.sock fail_timeout=0;
}

server {
  listen 80 default_server deferred;
  # server_name example.com;
  root /home/deploy/apps/awesomeapp/current/public;

  location ~ /downloads/(.*) {
    internal;
    alias /home/deploy/uploads/$1;
  }

  location ^~ /assets/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

  try_files $uri/index.html $uri @unicorn;
  location @unicorn {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    proxy_set_header X-Sendfile-Type X-Accel-Redirect;
    proxy_set_header X-Accel-Mapping /downloads/=/home/deploy/uploads/;

    proxy_pass http://unicorn;
  }

  error_page 500 502 503 504 /500.html;
  client_max_body_size 20M;
  keepalive_timeout 10;
}

【问题讨论】:

    标签: ruby-on-rails nginx http-headers


    【解决方案1】:

    好的,这里有一些东西。我不知道这是否正确,但我能够通过从我的 Rails Controller 手动发送 Content-Length 标头来解决问题。这就是我正在做的事情:

    def download
        @file = Attachment.find(params[:id])
    
        response.headers['Content-Length'] = @file.size.to_s
        send_file(@file.path, x_sendfile: true)
    end
    

    nginx 应该能够自动设置标题。一定有我想念的东西;但在我找到“合适”的解决方案之前,我想这将不得不这样做。

    P.S: Header 需要是一个字符串才能与某些网络服务器正常工作,因此 .to_s

    【讨论】:

      猜你喜欢
      • 2013-02-15
      • 1970-01-01
      • 2018-04-06
      • 1970-01-01
      • 2018-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      相关资源
      最近更新 更多