Skip to content

Serving Static Files

tobyclemson edited this page Sep 14, 2010 · 2 revisions

To serve static files, create a controller like this and put your static files in static/.

class Static < R '/static/(.+)'
  MIME_TYPES = {
    '.html' => 'text/html',
    '.css'  => 'text/css',
    '.js'   => 'text/javascript',
    '.jpg'  => 'image/jpeg',
    '.gif'  => 'image/gif'
  }
  PATH = File.expand_path(File.dirname(@__FILE__@))
  def get(path)
    @headers['Content-Type'] = MIME_TYPES[path[/\.\w+$/, 0]] || "text/plain" 
    unless path.include? ".." # prevent directory traversal attacks
      @headers['X-Sendfile'] = "#{PATH}/static/#{path}" 
    else
      @status = "403" 
      "403 - Invalid path" 
    end
  end
end

This was originally from http://code.whytheluckystiff.net/camping/wiki/ServingStaticFiles .

Clone this wiki locally