Run Sinatra App in a Subdirectory with Rack::Builder.map

Thank god I found Tanner Burson’s blog. I was about to explode. I recommend reading Tanner’s original post, but the short answer is that you want Rack to do some routing for you via Rack::Bundler.map. Here is a super simple example to get you running your Sinatra app in a subdirectory.

ronk.rb

require 'sinatra/base'

module Ronk

  class Foo < Sinatra::Base

    get '/' do
      'I am Foo'
    end
  end

  class Bar < Sinatra::Base

    get '/' do
      'I am Bar'
    end
  end

end

config.ru

require 'sinatra'
require File.join(File.dirname(__FILE__), 'ronk')

disable :run

map '/' do
  run Ronk::Foo
end

map '/bars' do
  run Ronk::Bar
end

nginx

Just for fun, let’s say you’re trying to reverse proxy through nginx.

(These are just the relevant parts. Google for a more thorough nginx or Apache configuration.)

proxy.conf

proxy_redirect          default;
proxy_set_header        Host                $host;
proxy_set_header        X-Real-IP           $remote_addr;
proxy_set_header        X-Forwarded-Host    $host;
proxy_set_header        X-Forwarded-Server  $host;
proxy_set_header        X-Forwarded-For     $proxy_add_x_forwarded_for;

nginx.conf

server {

  server_name  example.org;

  location / {
    proxy_pass http://localhost:9292/;
    include proxy.conf;
  }

  location /bars/ {
    proxy_pass http://localhost:9292/bars;
    include proxy.conf;
  }
}

Run the server

$ rackup # or unicorn, or thin, or whatever

Sample GETs

$ GET http://localhost:9292/
I am Foo
$ GET http://localhost:9292/bars/
I am Bar
This entry was posted in Sinatra and tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>