1

I have a Rails app that will soon be switching domain names. Since we don't want to break any old links, I'd like to set up 301 redirects for all requests using the old domain name. Everything about this is relatively straightforward except that there are a few routes that use subdomains.

What essentially needs to happen is this:

  • 'olddomain.com/somepath' (301) ~> 'newdomain.com/somepath'
  • 'subdomain.olddomain.com/somepath' (301) ~> 'subdomain.newdomain.com/somepath'

Most suggestions I've seen for this issue generally fall into one of two categories.

  1. There aren't any subdomains involved
  2. The redirects all involve a consistent subdomain which can be included as part of the host when redirecting

In my situation the majority of requests will not have subdomains, however there are a few that will.

It's easy enough to separate the HTTP_HOST (request.env['HTTP_HOST']) into its subdomain and domain components, compare the domain on the incoming request with the application's new domain and if they don't match, redirect to the new uri (incoming request protocol + (potentially) subdomain + new domain + request path), but for some reason it feels very messy and I imagine there's a cleaner way to accomplish the same thing.

Here it is as (slightly more readable) pseudocode:

  • if a subdomain is present on incoming request, take request.env['HTTP_HOST'] and remove subdomain to get just the domain
  • compare the domain name on the incoming request with the new domain name
    • if they match, no redirect
    • if they don't match, redirect
      • if request includes a subdomain, include the subdomain in the redirect uri
      • if no subdomain, leave subdomain out of redirect uri

Like I mentioned, the conditionals make it feel messy.

I don't mind using a controller-level solution instead of messing with middleware as this is unlikely to be in place for very long. Any suggestions for approaches to consider and/or resources to look at would be much appreciated.

0 Answers0