Show:

Simple Rack app for 301 redirects

September 7, 2017 Programming

We created AxiomQ by merging two companies. Both of them had their own sites. To keep search engines happy we need to setup 301 redirects. Unfortunately, one site was running on Github Pages which doesn’t support 301 redirects.

The solution was to create a simple Rack app, use rack-rewrite gem to redirect traffic, and deploy it on Heroku.

Rack-rewrite is a nice gem which implements a rack middleware that acts similar to Apache mod_rewrite. Rewrite rules are simple to define. I encourage you to take a look at rack-rewrite docs.

We only needed the most simple 301 http redirect which redirects a page to new URL. Like this one redirecting about page to new team page:

r301 %r{/about}, 'https://www.axiomq.com/team/'

Most basic Rack application only requires a config.ru file, but for ease of use and simpler deployment we also added a Gemfile.

# Gemfile
source 'https://rubygems.org'

gem 'rack'
gem 'rack-rewrite'

# config.ru
require 'rack/rewrite'

use Rack::Rewrite do
  r301 %r{/about}, 'https://www.axiomq.com/team/'
  r301 %r{/contact}, 'https://www.axiomq.com/contact/'
  # ... more redirects ...
end

run lambda { |env| [301, {'Location'=>'https://www.axiomq.com/'}, StringIO.new("")] }

r301 lines define every redirect we need (you can also use regular expressions). The last line is a catch-all redirect just in case we missed something – it will still be redirected to new site homepage.

To try this app locally you can use rackup like this:

bundle exec rackup -p 9292 config.ru

Finally deploying to Heroku is really simple as pure Rack apps are supported by Heroku. Just follow the usual setup outlined in their documentation for deploying Rack apps to Heroku.