Daniel Fischer
Daniel Fischer

Reputation: 3062

Force Rails Heroku App from subdomain.herokuapp.com to apex domain?

What is the proper way to send a subdomain.herokuapp.com to the apex domain of the application? This is to avoid multiple domain names with the same content.

Upvotes: 5

Views: 1570

Answers (3)

King'ori Maina
King'ori Maina

Reputation: 4507

For a comprehensive answer with some bit of extensibility, in totality it looks something like this;

class ApplicationController < ActionController::Base

  before_filter :redirect_to_example if Rails.env.production?

  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  private

    # Redirect to the appropriate domain i.e. example.com
    def redirect_to_example
      domain_to_redirect_to = 'example.com'
      domain_exceptions = ['example.com', 'www.example.com']
      should_redirect = !(domain_exceptions.include? request.host)
      new_url = "#{request.protocol}#{domain_to_redirect_to}#{request.fullpath}"
      redirect_to new_url, status: :moved_permanently if should_redirect
    end
end

This will redirect everything to domain_to_redirect_to except what's in domain_exceptions.

Upvotes: 2

manoj
manoj

Reputation: 1675

Quoting from https://devcenter.heroku.com/articles/custom-domains

The domain myapp.herokuapp.com will always remain active, even if you’ve set up a custom domain. If you want users to use the custom domain exclusively, you 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 myapp.herokuapp.com.

You can redirect requests to the "subdomain.herokuapp.com" using a before filter in ApplicationController or using a constraint in rails routing.

Upvotes: 6

Daniel Fischer
Daniel Fischer

Reputation: 3062

https://github.com/tylerhunt/rack-canonical-host seems to be the perfect choice for this. Leaving it here for anyone else who has the same question.

Upvotes: 9

Related Questions