如何通过 Rack 提供静态文件? [英] How to serve static files via Rack?
问题描述
我目前正在开发一个基于 Rack 的应用程序,并希望将所有文件请求(例如 filename.filetype
)重定向到指定的文件夹.
I am currently developing a Rack-based application and want to redirect all file requests (e.g. filename.filetype
) to a specified folder.
Rack::Static
仅支持对特殊文件夹(例如/media")的文件请求.
Rack::Static
only supports file requests for a special folder(e.g. "/media").
我是否必须编写自己的 Rack 中间件或是否存在开箱即用的解决方案?
Do I have to write my own Rack middleware or does an out-of-the-box solution exist?
推荐答案
要将每个请求重定向到特定路径,请使用 Rack::File
(由于某种原因,这个类在最近的文档中不存在,但它是 仍然是最新 Rack 的一部分):
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")
要重定向每个请求,并在目标目录中添加所有文件的 HTML 索引,请使用 Rack::Directory
:
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
这篇关于如何通过 Rack 提供静态文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!