开发者

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

开发者 https://www.devze.com 2023-03-25 01:45 出处:网络
I was wondering if there was a Rack alternative to forcing the \'www\' in the URL since Heroku doesn\'t 开发者_如何学运维use .htaccess files.

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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消