Redirect 'myapp.com' to 'www.myapp.com' in rails without using htaccess?
Maybe something like this would do the trick:
class ApplicationController < ActionController::Base before_filter :check_uri def check_uri redirect_to request.protocol + "www." + request.host_with_port + request.request_uri if !/^www/.match(request.host) endend
Carson's answer works great.
Here's the code to go the other way (www -> no www)
before_filter :check_uridef check_uri if /^www/.match(request.host) redirect_to request.protocol + request.host_with_port[4..-1] + request.request_uri endend
I had to change Carson's answer to get this to work in Rails 3. I replaced request.uri with request.fullpath:
class ApplicationController < ActionController::Base protect_from_forgery Rails.env.production? do before_filter :check_url end def check_url redirect_to request.protocol + "www." + request.host_with_port + request.fullpath if !/^www/.match(request.host) endend