简体   繁体   中英

example.herokuapp.com redirection to https://example.com

I have a rails app deployed on heroku, domain by google and DNS by cloudflare. I would like to redirect all the requests that come to example.herokuapp.com to example.com . I can't set this on cloudflare, since if I use a page rule that would send the traffic from example.herokuapp.com to example.com then cloudflare raises this error: ERROR Your URL should reference the domain 'example.com' in some way.

I also checked on heroku, but I don't really get what I should do:

"Your app's Heroku Domain will always remain active, even if you've set up a custom domain. If you want users to use the custom domain exclusively, your app should send HTTP status 301 Moved Permanently to tell web browsers to use the custom domain. The Host HTTP request header field will show which domain the user is trying to access; send a redirect if that field is example.herokuapp.com."

What is the preferred way to redirect the traffic to the https://example.com ?

UPDATE

application.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

I use rack-rewrite for this.

First add it to your Gemfile:

gem 'rack-rewrite'

Then run bundle install .

Now add the following to your config.ru file:

require 'rack-rewrite'

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

If the request is not for example.com then it will do a 301 redirect to https://example.com

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM