Home > Coding, GNU/Linux, Heroku, Rack, Ruby > redirect domain using rack on rails on heroku

redirect domain using rack on rails on heroku


Sudah satu minggu, kita ngoding ruby ngoprek lagi 😀 . masi dengan ruby.

kemarin sempet ngoprek RoR atau ruby on rails, ya iseng2 disaat sengggang kalo pas bosen ngadmin :D. ketemu masalah gimana cara bikin domain yang ada di heroku dengan aplikasi RoR hanya 1atau 2 lebih domain yg menghandle nya.

berikut contohnya:

Multiple domain list:
1. devel.heroku.com
2. coderiver.alinux.web.id

add on your environment.rb :

require  'lib/domainredirect.rb'
# This is how you use and configure Rack::DomainRedirect middleware
config.middleware.use Rack::DomainRedirect, ['coderiver.alinux.web.id', '192.168.0.177']

put `domainredirect.rb` on lib directory:

module Rack

  # Automatically redirects to the configurable domain
  #
  # If request comes from other than specified domains it redirects to the first
  # domain from the list
  class DomainRedirect

    def initialize(app, hosts = [])
      @app = app
      @hosts = hosts
    end

    def call(env)
      req = Rack::Request.new(env)

      if @hosts.nil? or @hosts.empty? or @hosts.include?(req.host)
        @app.call(env)
      else
        url = "http://#{@hosts[0]}"
        # url << ":#{req.port}" unless req.port == 80
        url << "#{req.path}"
        url << "?#{req.query_string}" unless req.query_string.empty?
        res = Rack::Response.new
        res.redirect(url)
        res.finish
      end
    end
  end
end

binggo !! coba test devel.heroku.com nanti lari ke coderiver.alinux.web.id 😀

real worlds: devel.heroku.com

ref:
1. http://blog.misza.co.uk/2010/01/redirecting-in-rack.html
2. http://guides.rubyonrails.org/railsonrack.html

Advertisements
  1. April 17, 2011 at 11:17 am

    Sempurna…. 🙂

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s