Ideally, you should configure these rules in your web server settings. Requests will be faster because they wonβt even reach the rail stack. There was no need to add code to your application.
However, if you work in some limited environment, for example heroku, I would advise adding rack middleware. (Only for recommendations, cannot guarantee that this particular code is an error)
class Redirector SUBDOMAIN = 'www' def initialize(app) @app = app end def call(env) @env = env if redirect? redirect else @app.call(env) end end private def redirect?
You can also test all this in isolation.
describe Redirector do include Rack::Test::Methods def default_app lambda { |env| headers = {'Content-Type' => "text/html"} headers['Set-Cookie'] = "id=1; path=/\ntoken=abc; path=/; secure; HttpOnly" [200, headers, ["default body"]] } end def app() @app ||= Rack::Lint.new(Redirector.new(default_app)) end it "redirects unsupported subdomains" do get "http://example.com/zomg?a=1" last_response.status.should eq 301 last_response.header['location'].should eq "http://www.example.com/zomg?a=1" end
Then you can add it only to production (or to any preferred environment)
# production.rb
If you want to test it in development, add the same line to development.rb and add an entry to your hosts file (usually / etc / hosts) to treat yoursubdomain.localhost as 127.0.0.1
source share