不使用htaccess,将’myapp.com’重定向到rails中的’www.myapp.com’?
使用Morph Labs的Appspace部署站点意味着没有自动方式将“myapp.com”重定向到“www.myapp.com”(并且无法访问.htacess)。
有这样的轨道方式吗? 我需要一个像subdomain-fu这样的插件吗?
更具体地说,我正在尝试做类似的事情:
- ‘myapp.com’=>’www.myapp.com’
- ‘myapp.com/session/new’=>’www.myapp.com/session/new’
基本上,我总是希望每个请求都附加“www”子域名(因为SSL证书的具体名称是“www.myapp.com”)。
也许这样的事情可以解决问题:
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) end end
卡森的回答很有效。
这是代码走另一条路(www – >没有www)
before_filter :check_uri def check_uri if /^www/.match(request.host) redirect_to request.protocol + request.host_with_port[4..-1] + request.request_uri end end
我不得不改变Carson的答案,让它在Rails 3中运行。我用request.fullpath替换了request.uri:
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) end end
这对我很有用。 我确实做了一个小的补充,因为我只想在我的生产环境中使用这种行为:
def check_uri redirect_to request.protocol + "www." + request.host_with_port + request.request_uri if !/^www/.match(request.host) if Rails.env == 'production' end
我知道这已得到解答,但我认为其他人都应该了解CodeRack:Canonical Host解决方案。 这非常好,因为它允许env特定的重定向。 http://coderack.org/users/tylerhunt/middlewares/6-canonical-host
这有几种不同的方式:
head :moved_permanently, :location => 'http://www.newdomain.com'
另一个:
def rails_301 headers["Status"] = "301 Moved Permanently" redirect_to "http://www.newdomain.com" end
对于那些希望使用heroku强制SSL的人来说,这对我来说很有效,基于根域上的Heroku SSL
在我的DNS设置中,我设置了一个URL /转发记录(DNS简单)
URL foo.com 3600 http://www.foo.com
只需要为WWW设置CNAME设置
CNAME www.foo.com 3600 providedssslendpoint.herokussl.com
我还必须为我的root设置和Alias
ALIAS foo.com 3600 providedsslendpoint.herokussl.com
然后我决定简单地用env变量ENV['SITE_HOST']
替换foo.com (其中SITE_HOST可能等于www.foo.com或test.foo.com)所以我可以通过我的heroku配置进行控制。 这样,我可以控制在不同环境中发生的事情。 (用于在本地设置env变量,请参阅https://github.com/bkeepers/dotenv )
例如,我的测试应用程序使用test.foo.com作为url它也有自己的SSL端点,所以对我来说工作正常。
before_filter :check_domain def check_domain if Rails.env.production? || Rails.env.testing? and request.host.downcase != ENV['SITE_HOST'] redirect_to request.protocol + ENV['SITE_HOST'] + request.fullpath, :status => 301 end end
从现在开始,最终用户将始终使用强制SSL访问www。 旧的链接将遭受小挂,但没有什么值得注意的。