我在Heroku(例如 www.example.com)上部署了一个网站,并且我已经设置CloudFlare为我的CDN,因此我网站的所有流量都通过 CloudFlare。
但是我在子域(example.heroku.com)上仍然有我的应用程序的链接Heroku,如果有人尝试这个地址,它就不会再通过CloudFlare了。
如何隐藏我的 Heroku 应用程序地址 (example.heroku.com) 并使我的网站只接受来自 CloudFlare 的流量?
我在Heroku(例如 www.example.com)上部署了一个网站,并且我已经设置CloudFlare为我的CDN,因此我网站的所有流量都通过 CloudFlare。
但是我在子域(example.heroku.com)上仍然有我的应用程序的链接Heroku,如果有人尝试这个地址,它就不会再通过CloudFlare了。
如何隐藏我的 Heroku 应用程序地址 (example.heroku.com) 并使我的网站只接受来自 CloudFlare 的流量?
我的回答是基于您使用 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