Rails + Heroku + Cloudflare - Eliminate www as a subdomain

343 views Asked by At

I have a multi-tenant Rails 4 app that uses subdomains with PostgreSQL schemas to 'tenant' the application. I have the subdomain wildcards "*" set up in Heroku and Cloudflare and the site loads, but it keeps "thinking" that the www is a valid subdomain. Because of this, normally valid links (that work in development) do not work in production because www.mysite.com/accounts/new etc. is the same as asdf.mysite.com/accounts/new. Is there any way I can get my app to pretty much ignore www as a subdomain? I'd still like mysite.com to re-direct to www.mysite.com, but pretty much just set the subdomain to false when it is www?

To make things a little more concrete, in my application_controller, I have some code that does the following. Notice the comments. In development mode, the redirect_to root_url(subdomain: false) works, but in production, it just infinitely re-directs and will not load. To get it to load, I simply render the page, but doing so never sets the subdomain to false.

  def load_schema
    Apartment::Tenant.switch!('public')
    return unless request.subdomain.present?
    if current_account
      Apartment::Tenant.switch!(current_account.subdomain)
    else
      redirect_to root_url(subdomain: false) # Works locally, but infinite re-direct in production
      #render 'welcome/index' # - Renders the page in production, but nothing else works.
    end
  end

Basically, everything works as expected in development mode, but in production, there appear to be some DNS issues that need ironed out, but I can't seem to figure out what to do. Any thoughts?

2

There are 2 answers

0
Trinculo On BEST ANSWER

I had to remove the A name record in CloudFlare and replace it with a CNAME record. I also added 2 additional CNAME records: one wildcard and one for www.

1
Simone Carletti On

My suggestion is to force www.mysite.com to redirect to mysite.com where you probably have the main site.

You can either accomplish it using pointing the hostname to a redirect service, or using a specific route with constraint in the routes.rb file.