Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force 'www' in Rails3 hosted on Heroku without .htaccess

I was wondering if there was a Rack alternative to forcing the 'www' in the URL since Heroku doesn't use .htaccess files.

Maybe even a nice way to do it in routes?

Thanks

like image 886
scott Avatar asked Oct 26 '25 04:10

scott


1 Answers

In your ApplicationController, you can simply create a before filter:

before_filter :force_www!

protected

def force_www!
  if Rails.env.production? and request.host[0..3] != "www."
    redirect_to "#{request.protocol}www.#{request.host_with_port}#{request.fullpath}", :status => 301
  end
end

Or to go the other direction and remove www:

before_filter :remove_www!

protected

def remove_www!
  if Rails.env.production? and request.host[0..3] == "www."
    redirect_to "#{request.protocol}#{request.host_with_port[4..-1]}#{request.fullpath}", :status => 301
  end
end
like image 93
Adrian Macneil Avatar answered Oct 29 '25 09:10

Adrian Macneil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!