301 Redirects for Octopress

I’ve finally changed the default route path, domain/blog, used by Octopress which will remove the uselesss /blog after the domain.

Since this is changing the site’s URL structure it’s extremely important all old URLs are redirected correctly. To setup 301 redirects I’ve always used .htaccess, but Heroku doesn’t use Apache and .htaccess won’t work. My solution came from using the rack-rewrite gem.

rack-rewrite

a rack middleware for defining and applying rewrite rules. In many cases you can get away with rack-rewrite instead of writing Apache mod_rewrite rules.

In order to implement rack-rewrite on Heroku you need edit your Gemfile to include the rack-rewrite gem:

source "https://rubygems.org"

group :development do
  gem 'rake', '~> 0.9'
  gem 'jekyll', '~> 0.12'
  gem 'rdiscount', '~> 2.0.7'
  gem 'pygments.rb', '~> 0.3.4'
  gem 'RedCloth', '~> 4.2.9'
  gem 'haml', '~> 3.1.7'
  gem 'compass', '~> 0.12.2'
  gem 'sass', '~> 3.2'
  gem 'sass-globbing', '~> 1.0.0'
  gem 'rubypants', '~> 0.2.0'
  gem 'rb-fsevent', '~> 0.9'
  gem 'stringex', '~> 1.4.0'
  gem 'liquid', '~> 2.3.0'
end

gem 'sinatra', '~> 1.4.2'
gem 'rack-rewrite'

Now add your rewrite rules (after $root) to your config.ru file:

require 'bundler/setup'
require 'sinatra/base'
require 'rack-rewrite'

# The project root directory
$root = ::File.dirname(__FILE__)

use Rack::Rewrite do
    r301 %r{^/blog/2015/02/06/google-play-one-time-nexus-5-replacement/?$}, 'http://blog.wadegarrett.com/2015/02/06/google-play-one-time-nexus-5-replacement/'

Lastly execute bundle in the root of your project to install the rake-rewrite gem and that’s it.

Google+