Search code examples
ruby-on-railsherokuroutessubdomain

Using rails domain constraints with heroku subdomains


I have a rails app with two subdomains configured as such in routes.rb

Rails.application.routes.draw do
  constraints subdomain: 'admin' do
    devise_for :admin_users, ActiveAdmin::Devise.config
    ActiveAdmin.routes(self)
  end

  namespace :api, defaults: { format: :json },
            constraints: { subdomain: 'api' }, path: '/' do

    scope module: :v1,
          constraints: ApiConstraints.new(version: 1, default: true) do
      resources :countries, only: [:show, :index]
    end

  end
end

This works perfectly locally. My /etc/hosts looks like

admin.localhost.local localhost
api.localhost.local   localhost

But when it comes to configure this in Heroku, things don't work as supposed to.

I configured my DNS and the Heroku's custom domain to be like this:

admin.my_project.my_domain.com -> admin.my_project.my_domain.com.herokudns.com
api.my_project.my_domain.com -> api.my_project.my_domain.com.herokudns.com

But when I access http://admin.my_project.my_domain.com I get an routing error 404

And the logs have this:

heroku[router]: at=info method=GET path="/" host=admin.my_project.my_domain.com request_id=XXX fwd="IP.IP.IP.IP" dyno=web.1 connect=0ms service=3ms status=404 bytes=1744 protocol=http
app[web.1]: INFO -- : Started GET "/" for IP.IP.IP.IP at 2017-03-14
app[web.1]: FATAL -- : ActionController::RoutingError (No route matches [GET] "/"):

Meaning that when getting the request, Rails doesn't know that it's coming from a subdomain.

How can I make this work? Thanks


Solution

  • Ok, I've solved it.

    I needed to add this to the config/environments/production.rb

      config.action_dispatch.tld_length = 2
    

    So that the subdomain was properly selected.