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

强颜欢笑 提交于 2019-12-04 12:54:07

A quick Google search reveals this Rack middleware, which appears to do exactly what you want.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!