在 Rails 中将“myapp.com”重定向到“www.myapp.com”而不使用 htaccess?
-
11-07-2019 - |
题
使用 Morph Labs 的 Appspace 部署站点意味着无法自动将“myapp.com”重定向到“www.myapp.com”(并且无法访问 .htacess)。
有没有一种轨道内的方法可以做到这一点?我需要一个像这样的插件吗 子域-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:规范主机解决方案。这真的很好,因为它允许特定于环境的重定向。 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
我还必须为我的根设置和别名
ALIAS foo.com 3600 providedsslendpoint.herokussl.com
然后我决定简单地替换 foo.com 带有环境变量 ENV['SITE_HOST']
(其中 SITE_HOST 可能等于 www.foo.com 或 test.foo.com),因此我可以通过我的 heroku 配置进行控制。这样,我就可以控制不同环境中发生的事情。(要在本地设置环境变量,请参阅 https://github.com/bkeepers/dotenv)
例如,我的测试应用程序使用 测试.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。旧的链接会出现轻微的挂起,但不会引起任何明显的影响。