Search code examples
rubyurlsinatrarackradix

Is it possible to to rewrite the base URL in Sinatra?


Is it possible to to rewrite the base URL?

E.g. instead of www.host.com/ to use www.host.com/blah/ as a base url and so:

get '/' do
  ...
end

would work for www.host.com/blah/

I could append to all my routes '/blah/..' but any gems etc. would fail to work as well.

This can be done in Rails easily and I would like to have it in Sinatra as well.


Solution

  • I use a rack middleware for this rack-rewrite and I am quite happy with it :)

        use Rack::Rewrite do
          rewrite %r{^/\w{2}/utils}, '/utils'
          rewrite %r{^/\w{2}/ctrl},  '/ctrl'
          rewrite %r{^/\w{2}/},      '/'
        end
    

    EDIT:

    Not sure if I understand your problem, but here are a config.ru file

    # encoding: utf-8
    require './config/trst_conf'
    require 'rack-flash'
    require 'rack/rewrite'
    
    use Rack::Session::Cookie, :secret => 'zsdgryst34kkufklfSwsqwess'
    use Rack::Flash
    use Rack::Rewrite do
      rewrite %r{^/\w{2}/auth},  '/auth'
      rewrite %r{^/\w{2}/utils}, '/utils'
      rewrite %r{^/\w{2}/srv},   '/srv'
      rewrite %r{^/\w{2}/},      '/'
    end
    
    map '/auth' do
      run TrstAuth.new
    end
    map '/utils' do
      run TrstUtils.new
    end
    map '/srv' do
      map '/tsk' do
         run TrstSysTsk.new
      end
      map '/' do
        run TrstSys.new
      end
    end
    map '/' do
      run TrstPub.new
    end
    

    and an example Sinatra::Base subclass

    # encoding: utf-8
    
    class TrstAuth < Sinatra::Base
    
      # Render stylesheets
      get '/stylesheets/:name.css' do
        content_type 'text/css', :charset => 'utf-8'
        sass :"stylesheets/#{params[:name]}", Compass.sass_engine_options
      end
    
      # Render login screen
      get '/login' do
        haml :"/trst_auth/login", :layout => request.xhr? ? false : :'layouts/trst_pub'
      end
    
      # Authentication
      post '/login' do
        if user = TrstUser.authenticate(params[:login_name], params[:password])
          session[:user] = user.id
          session[:tasks] = user.daily_tasks
          flash[:msg] = {:msg => {:txt => I18n.t('trst_auth.login_msg'), :class => "info"}}.to_json
          redirect "#{lang_path}/srv"
        else
          flash[:msg] = {:msg => {:txt => I18n.t('trst_auth.login_err'), :class => "error"}}.to_json
          redirect "#{lang_path}/"
        end
      end
    
      # Logout
      get '/logout' do
        session[:user] = nil
        session[:daily_tasks] = nil
        flash[:msg] = {:msg => {:txt => I18n.t('trst_auth.logout_msg'), :class => "info"}}.to_json
        redirect "#{lang_path}/"
      end
    
    end
    

    maybe this helps :) full source on github.