41

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 only supports file requests for a special folder(e.g. "/media").

Do I have to write my own Rack middleware or does an out-of-the-box solution exist?

Anton Menshov
  • 2,266
  • 14
  • 34
  • 55
brainfck
  • 9,286
  • 7
  • 28
  • 29

4 Answers4

40

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
molf
  • 73,644
  • 13
  • 135
  • 118
  • I had to wrap the run MyApp.new with map "/" do .. end. Otherwise I was getting an undefined call method error. (No idea why.) – Venkat D. Apr 05 '11 at 00:31
14

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.

Srikanth Venugopalan
  • 9,011
  • 3
  • 36
  • 76
11

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
kejadlen
  • 1,519
  • 1
  • 10
  • 10
2
run Rack::Directory.new(Dir.pwd)
Diego Carrion
  • 513
  • 5
  • 8