27

使用 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”)。

4

7 回答 7

30

也许这样的事情可以解决问题:

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
于 2008-11-29T04:14:05.720 回答
8

卡森的回答效果很好。

这是另一种方式的代码(www -> no 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
于 2009-11-13T14:55:44.970 回答
5

我必须更改 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
于 2012-03-01T19:04:18.890 回答
2

这对我很有用。我确实做了一个小的补充,因为我只希望在我的生产环境中出现这种行为:

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
于 2010-06-28T00:16:31.123 回答
1

我知道这已经得到解答,但我认为其他人都应该知道 CodeRack:Canonical Host 解决方案。这非常好,因为它允许特定于 env 的重定向。http://coderack.org/users/tylerhunt/middlewares/6-canonical-host

于 2010-07-25T20:18:06.810 回答
0

这里有几种不同的方法:

 head :moved_permanently, :location => ‘http://www.newdomain.com’

其他:

def rails_301
headers["Status"] = "301 Moved Permanently"
redirect_to "http://www.newdomain.com"
end 
于 2008-11-29T03:45:44.530 回答
0

对于那些希望也使用 heroku 强制 SSL 的人来说,这对我来说效果很好,基于根域上的 Heroku SSL

在我的 DNS 设置中,我设置了一个 URL / 转发记录(DNS 简单)

URL foo.com     3600        http://www.foo.com

CNAME 设置只需要为 WWW 设置

CNAME   www.foo.com 3600        providedssslendpoint.herokussl.com

我还必须为我的根设置和别名

ALIAS   foo.com 3600        providedsslendpoint.herokussl.com

然后我决定简单地将foo.com替换为 env 变量ENV['SITE_HOST'](其中 SITE_HOST 可能等于 www.foo.com 或 test.foo.com),这样我就可以通过我的 heroku 配置进行控制。这样,我可以控制在不同环境中发生的事情。(有关在本地设置环境变量,请参阅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。旧链接会出现小问题,但没有什么明显的。

于 2013-10-16T05:37:55.673 回答