2

How do this:

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

in rack-rewrite syntax?

Greg Betr
  • 21
  • 3

1 Answers1

2

You can create a new middleware for this

class SubdomainToWwwMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    request = Rack::Request.new(env)
    if !request.host.starts_with?("www.")
      [301, { "Location" => request.url.gsub(/\/\/([^\.]*)/, "//www") }, self]
    else
      @app.call(env)
    end
  end
end

This is untested but should put you in the right direction. You will likely want to add a condition to check not just for www.example.com but also example.com. The middleware above might blow up currently in that case.

You can put this in /lib/middleware/subdomain_to_www_middleware.rb, add

config.autoload_paths += %W( #{ config.root }/lib/middleware )

to your config/application.config, and

config.middleware.use "SubdomainToWwwMiddleware"

to your config/environments/production.rb

deefour
  • 34,974
  • 7
  • 97
  • 90
  • I followed your steps and got the error: TypeError (can't convert Regexp into String): lib/middleware/subdomain_to_www_middleware.rb:9:in `gsub' lib/middleware/subdomain_to_www_middleware.rb:9:in `call' – Greg Betr Nov 15 '12 at 15:06