【问题标题】:example.herokuapp.com redirection to https://example.comexample.herokuapp.com 重定向到 https://example.com
【发布时间】:2016-06-21 14:31:06
【问题描述】:

我在 heroku 上部署了一个 rails 应用程序,Google 的域和 cloudflare 的 DNS。我想将所有来自example.herokuapp.com 的请求重定向到example.com。我不能在 cloudflare 上设置这个,因为如果我使用一个页面规则将流量从 example.herokuapp.com 发送到 example.com 那么 cloudflare 会引发这个错误:ERROR Your URL should reference the domain 'example.com' in some way.

我也检查了heroku,但我真的不明白我应该做什么:

“即使您设置了自定义域,您的应用程序的 Heroku 域也将始终保持活动状态。如果您希望用户独占使用自定义域,您的应用程序应发送 HTTP 状态 301 Moved Permanently 以告知 Web 浏览器使用自定义域。Host HTTP 请求标头字段将显示用户尝试访问的域;如果该字段是 example.herokuapp.com,则发送重定向。"

将流量重定向到https://example.com 的首选方式是什么?

更新

应用程序.rb

config.middleware.insert_before(Rack::Runtime, Rack::Rewrite) do
  r301 %r{.*}, "https://example.com$&", 
  :if => Proc.new { |rack_env| rack_env['SERVER_NAME'] != 'example.com' }
end

【问题讨论】:

    标签: ruby-on-rails heroku dns cloudflare


    【解决方案1】:

    我为此使用rack-rewrite

    首先将其添加到您的 Gemfile:

    gem 'rack-rewrite'
    

    然后运行bundle install

    现在将以下内容添加到您的 config.ru 文件中:

    require 'rack-rewrite'
    
    use Rack::Rewrite do
      r301 %r{.*}, "https://example.com$&", :if => Proc.new {|rack_env|
        rack_env['SERVER_NAME'] != 'example.com'
      }
    end
    

    如果请求不是针对example.com,那么它将执行301 重定向到https://example.com

    【讨论】:

    • 注入了,我查看了文档,但不是很清楚。我使用的是 rails 4.2.4,文档推荐了一些不同的代码。你能看看我更新的问题,我有我打算根据文档使用的代码吗?如果我在没有定义环境的情况下拥有它,你能否告诉我这段代码是否会破坏开发环境。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    • 2020-09-24
    • 2015-05-21
    • 1970-01-01
    • 2011-07-06
    • 2011-08-12
    相关资源
    最近更新 更多