Render static files in /doc in Rails

China☆狼群 提交于 2020-01-14 05:55:46

问题


So far I have in config/routes.rb:

match 'doc/:path' => 'doc#show'

And in app/controllers/doc_controller.rb:

class DocController < ApplicationController
  layout false

  def show
    render File.join( RAILS_ROOT, 'doc', params[:path] )
  end
end

This works find for index.html and other .html files. But it doesn't serve up .css and .js files. It also doesn't serve nested files and directories such as /doc/metrics/output/index.html

How can I get Rails to serve up all static files in /doc but without simply putting a link to them in /public (so that I can autheticate the user in the controller first)?


回答1:


I would recommend not serving the files through Rails at all. Serve them through your server (Nginx, Apache). You can use the X-Accel-Redirect and the X-Sendfile headers to tell Nginx and Apache to send the static file instead. The benefit of this approach is that you can still authenticate a user before allowing them access to the file. Here's the Nginx tutorial:

http://ablogaboutcode.com/2010/11/19/serving-static-files-passenger-nginx/

Another option is to setup your routes like this:

match 'doc' => 'doc#show'

And pass your path as a parameter so you don't have to do nested URL matching in your routes, or handle special cases (.css, .js, .html, ...)

/doc?path=/path/to/my/document.css


来源:https://stackoverflow.com/questions/4889200/render-static-files-in-doc-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!