tylerhunt (owner)

Forks

Revisions

gist: 206213 Download_button fork
public
Description:
Rack middleware that redirects requests to a canonical host.
Public Clone URL: git://gist.github.com/206213.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class CanonicalHost
  def initialize(app, host=nil, &block)
    @app = app
    @host = (block_given? && block.call) || host
  end
 
  def call(env)
    if url = url(env)
      [301, { 'Location' => url }, ['Redirecting...']]
    else
      @app.call(env)
    end
  end
 
  def url(env)
    if @host && env['SERVER_NAME'] != @host
      url = Rack::Request.new(env).url
      url.sub(%r{\A(https?://)(.*?)(:\d+)?(/|$)}, "\\1#{@host}\\3/")
    end
  end
  private :url
end