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....

Answers


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

Need Your Help

Comboboxes only load when selecting the second items and below

c# winforms combobox

This is really strange. I want to select a State and load Cities from that State in another combobox.

Send email with Sendgrid WebAPI and Cron PHP

php cron crontab sendgrid

I'm using the following standard Sendgrid WebAPI code in a PHP file which sends email successfully when accessed through the web browser and with Cron wget. However, when I try to execute it with C...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.