强制Rails Heroku App从subdomain.herokuapp.com到顶点域?

将subdomain.herokuapp.com发送到应用程序的顶点域的正确方法是什么? 这是为了避免具有相同内容的多个域名。

引自https://devcenter.heroku.com/articles/custom-domains

即使您已设置自定义域,域myapp.herokuapp.com也将始终保持活动状态。 如果您希望用户专门使用自定义域,则应发送HTTP状态301 Moved Permanently以告知Web浏览器使用自定义域。 主机HTTP请求标头字段将显示用户尝试访问的域; 如果该字段是myapp.herokuapp.com,则发送重定向。

您可以使用ApplicationController中的beforefilter或使用rails routing中的约束将请求重定向到“subdomain.herokuapp.com”。

对于具有一定可扩展性的综合答案,总体来说它看起来像这样;

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 ie 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 

除了domain_to_redirect_to之外,这会将所有内容重定向到domain_to_redirect_to