How to serve static files via Rack?

三世轮回 提交于 2019-11-27 17:27:12

To redirect every request to a particular path, use Rack::File (for some reason this class is absent in recent documentation, but it is still part of the latest Rack):

run Rack::File.new("/my/path")

To redirect every request, and add an HTML index of all files in the target dir, use Rack::Directory:

run Rack::Directory.new("/my/path")

To combine several directories or serve only a some requests from the target dir:

map "/url/prefix" do
  run Rack::File.new("/my/path")
end

# More calls to map if necessary...

# All other requests.
run MyApp.new

An update, the latest Rack implementation allows you to use Rack::Static

Example:

use Rack::Static, :urls => ["/media"]

Will serve all static resources under ./media folder relative to config.ru location.

You might be able to use Rack::File directly. Here's a config.ru file you can plug into rackup to see it work:

app = proc do |env|
  Rack::File.new('foo/bar').call(env)
end

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