Last Updated: February 25, 2016
·
3.361K
· petenicholls

Migrating from WordPress to Middleman, without breaking URLs

Lately, I've been building static sites using Stasis and, more recently, Middleman. They're great to work with, and perfect for blending the usefulness of a templating system with the simplicity and speed that comes with serving static files.

One of the sites I'm working on at the moment is a static-site rewrite of a bulky WordPress-powered system. What we're doing at the moment is transitioning the pages, one at a time, from one system to the other.

The trick? We're layering one site on top of the other using a plain-text Apache RewriteMap.

When we deploy the site, it goes through a build process. The build process generates the static version of the site on our server. At the end of the build process, we produce a routes.map file that looks like this:

/about /path/to/about.html
/resources /path/to/resources.html
...

We can then choose to layer one site on top of the other by adding a couple of RewriteRules to the VirtualHost directive (note: RewriteMaps only work inside a VirtualHost directive, not a .htaccess file):

# Enable rewrite engine
RewriteEngine on

# Declare a rewrite map that maps relative URL paths to static content
RewriteMap locale_map txt:/path/to/build/routes.map

# Use the map, if it contains a match
RewriteCond ${locale_map:$1} >""
RewriteRule ^(.*)$ ${locale_map:$1}

We essentially intercept the request that would normally be targeted for the underlying WordPress site and serve up our static content instead. If a request comes through that isn't accounted for inside the routes map, it simply continues on to the normal WordPress chain beneath.

The beauty of this code is it allows us to easily customise our static site's routing, and we can use it to support old URLs, custom redirects, or anything else we need.