Rails手动从裸域重定向

因此,由于我的托管服务提供商(Heroku)的限制,目前我手动指向裸域。 一切正常。 问题是,如果用户访问mydomain.com/route,重定向将发送回www.mydomain.com而不使用/ route。 我将如何重新添加路线,但仍然重定向到www。 ?

class ApplicationController  301 end end end end 

编辑

我从ApplicationController中删除了上面的代码,并选择使用hurikhan77建议的折射gem ,这解决了我的问题。

这是我使用的refraction_rules.rb。

 Refraction.configure do |req| if req.host == "domain.com" req.permanent! :host => "www.domain.com" end end 

我建议使用折射gem: http : //rubygems.org/gems/refraction

理想情况下,您可以在Web服务器配置中设置类似的规则。 请求会变得更快,因为它们甚至不会到达rails堆栈。 您也无需向应用添加任何代码。

但是,如果您在某些受限制的环境中运行,例如heroku,我建议添加机架中间件。 (仅供参考,不能保证此特定代码是否无错误)

 class Redirector SUBDOMAIN = 'www' def initialize(app) @app = app end def call(env) @env = env if redirect? redirect else @app.call(env) end end private def redirect? # do some regex to figure out if you want to redirect end def redirect headers = { "location" => redirect_url } [302, headers, ["You are being redirected..."]] # 302 for temp, 301 for permanent end def redirect_url scheme = @env["rack.url_scheme"] if @env['SERVER_PORT'] == '80' port = '' else port = ":#{@env['SERVER_PORT']}" end path = @env["PATH_INFO"] query_string = "" if !@env["QUERY_STRING"].empty? query_string = "?" + @env["QUERY_STRING"] end host = "://#{SUBDOMAIN}." + domain # this is where we add the subdomain "#{scheme}#{host}#{path}#{query_string}" end def domain # extract domain from request or get it from an environment variable etc. end end 

您也可以单独测试整个事物

 describe Redirector do include Rack::Test::Methods def default_app lambda { |env| headers = {'Content-Type' => "text/html"} headers['Set-Cookie'] = "id=1; path=/\ntoken=abc; path=/; secure; HttpOnly" [200, headers, ["default body"]] } end def app() @app ||= Rack::Lint.new(Redirector.new(default_app)) end it "redirects unsupported subdomains" do get "http://example.com/zomg?a=1" last_response.status.should eq 301 last_response.header['location'].should eq "http://www.example.com/zomg?a=1" end # and so on end 

然后,您只能将其添加到生产(或任何首选环境)

 # production.rb # ... config.middleware.insert_after 'ActionDispatch::Static', 'Redirector' 

如果要在开发中测试它,请将相同的行添加到development.rb并将记录添加到hosts文件(通常是/ etc / hosts)以将yoursubdomain.localhost视为127.0.0.1

不确定这是否是最佳解决方案,但您可以正确使用request.referrer并在.com之后删除任何内容并将其附加到APP_DOMAIN

或者我想你可以在第一次之前取出所有东西。 在request.env['HTTP_HOST']添加替换为http://www. 假设您不打算使用子域。