将Heroku设置为仅接受来自CloudFlare的流量

时间:2013-07-29 02:52:43

标签: heroku cloudflare

我在Heroku上部署了一个网站(例如www.example.com),我已将CloudFlare设置为我的CDN,因此我网站的所有流量都通过CloudFlare的。

但我仍然在Heroku子域(example.heroku.com)上有我的应用程序的链接,如果有人尝试此地址,它将不再通过CloudFlare

如何隐藏我的Heroku应用地址(example.heroku.com)并让我的网站仅接受来自CloudFlare的流量?

1 个答案:

答案 0 :(得分:1)

我的回答是基于您使用Heroku来托管Ruby Rack应用程序的假设,因为我认为这是大多数Heroku用户的个人资料。否则,请跳过。

如果你在Heroku上托管Rack应用程序,你可以插入一小段Rack中间件来为你做重定向。

# lib/rack/domain_redirect.rb
# encoding utf-8

# Rack Middleware that was created to handle
# autoredirecting requests away from *.herokuapp.com to
# the equivalent *.example.com. That said, it does allow you to configure
# what domain to redirect from and what domain to redirect to as well
module Rack
  class DomainRedirect

    attr_accessor :redirect_from_domain, :redirect_to_domain

    def initialize(app, redirect_from_domain = "herokuapp.com", redirect_to_domain = "example.com")
      self.redirect_from_domain = redirect_from_domain
      self.redirect_to_domain = redirect_to_domain
      @app = app
    end

    def call(env)
      request = Rack::Request.new(env)
      if request.host.include?(redirect_from_domain)
        [301, {"Location" => request.url.sub(redirect_from_domain, redirect_to_domain)}, []]
      else
        @app.call(env)
      end
    end

  end
end

然后在你的config.ru

# some other middlewares and requires

require File.expand_path("../lib/rack/domain_redirect.rb", __FILE__)
use Rack::DomainRedirect

# run your app
run MyApp