Blog

How to Redirect a Rails Application to a new Domain Name

Team Avatar - Mikel Lindsaar
Mikel Lindsaar
March 25, 2021

Rails Applications sometimes have their domain names swapped for something new. This can happen due to a rebranding, sale of the business or any other reason. In our case it was a rebranding. We had a Ruby on Rails application at https://storeconnect.app and it needed to be moved to https://GetStoreConnect.com.

Looking at the Rails Routing Guide I couldn’t see any obvious solution for doing this. I knew I could do it with a redirection Rack application, but I wanted something simple, a one liner even, in the routes.rb file, front and centre and easy to keep track of.

True to form, Rails came through with a simple and maintainable one liner to make it happen. I love working with this language and framework. This is how I did it:

ruby Rails.application.routes.draw do # Permanently redirect all requests originally to storeconnect.app to getstoreconnect.com get '/(*path)', to: redirect { |path_params, request| "https://getstoreconnect.com/#{path_params[:path]}" }, status: 301, constraints: { domain: 'storeconnect.app' } # ... Remaining application routes end

Simple.

The way it works, is we make a catch all route on get requests to the application. We put the *path matcher in there to capture anything after the forward slash. We use *path instead of :path so that we get everything, not just the next path segment, otherwise /about/location would not match.

We then also wrap *path in parenthesis to make it optional (otherwise just going to old-domain.com/ would not match).

Then we redirect all of these with a 301 to the new domain and pass the same path variable back in. We can’t use the shorthand method of redirect("https://getstoreconnect.com/%{path}") here because the path key may not be present and so would fail on matching the root domain.

We then put a constraint so that this will only match if the request domain is old-domain.com.

And there you go, a one liner (wrapped) :)