For completeness, you can use the rails' routing configuration to do this in Rails 4 using request-based routing constraints
This way has a small performance benefit over using your application controller in that the request doesn't need to hit your application code it's handled during Rails' routing middleware.
Place the following in your routes file (config/routes.rb
)
eg:
Rails.application.routes.draw do
# match urls where the host starts with 'www.' as long it's not followed by 'cute.'
constraints(host: /^www\.(?!cute\.)/i) do
match '(*any)', via: :all, to: redirect { |params, request|
# parse the current request url
# tap in and remove www.
URI.parse(request.url).tap { |uri| uri.host.sub!(/^www\./i, '') }.to_s
}
end
# your app's other routes here...
end