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

前端 未结 3 1479
迷失自我
迷失自我 2020-12-30 15:54

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.

3条回答
  •  攒了一身酷
    2020-12-30 16:08

    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.

提交回复
热议问题