cman77
cman77

Reputation: 1783

rewrite non www to www except subdomain rails 3 and rack

I need to be able to rewrite non www to www but NOT in the case when there is a (non www) subdomain present.

so example.com to-> www.example.com but sub.example.com remains sub.example.com

I'm in rails 3 and it seems this should be accomplished using Rack Middleware, but the snag is this is a multitenant app so the TLD could potentially be any domain.

This is where I am so far:

  Class Www

  def initialize(app)
    @app = app
  end

  def call(env)

    request = Rack::Request.new(env)

    if !request.host.starts_with?("www.")
      [301, {"Location" => request.url.sub("//","//www.")}, self]
    else
      @app.call(env)
    end

  end

  def each(&block)
  end

end

Any pointers would be appreciated....

Upvotes: 1

Views: 683

Answers (1)

Benoit Garret
Benoit Garret

Reputation: 13675

The code you have right now will rewrite "sub.example.com", your call function could be rewritten like this :

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

  # Redirect only if the host is a naked TLD
  if request.host =~ /^[^.]+\.[^.]+$/
    [301, {"Location" => request.url.sub("//","//www.")}, self]
  else
    @app.call(env)
  end
end

Upvotes: 1

Related Questions