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

筅森魡賤 提交于 2019-12-06 06:52:52

问题


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


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/6905664/force-www-in-rails3-hosted-on-heroku-without-htaccess

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