How to Redirect a Rails Application to a new Domain Name

Mikel Lindsaar
March 25, 2021

How to Redirect a Rails Application to a new Domain Name

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 and it needed to be moved to

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 to get '/(*path)', to: redirect { |path_params, request| "{path_params[:path]}" }, status: 301, constraints: { domain: '' } # ... Remaining application routes end


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 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("{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

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