Sean Magyar
Sean Magyar

Reputation: 2380

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

Upvotes: 0

Views: 642

Answers (1)

infused
infused

Reputation: 24337

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

Upvotes: 1

Related Questions