< Back
May 17, 2018

How to do a Rails redirect with a regex

I recently changed my blog from using numeral slugs (just the post IDs) to using proper text slugs based off of the title of the post. For SEO.

Unfortunately, Google remembers the times when I had post IDs for slugs, and Webmaster Tools has been emailing me regularly for the past few weeks letting me know that my site is throwing 500 errors when it’s trying to access the old indexed post-ID-based URLs.

Of course when you’re changing your URL schema you should always set up the redirects. But I didn’t.

Now I have. I wasn’t going to bother with redirecting the old post IDs to their respective posts because I’m a lazy so-and-so, so I decided to redirect anything matching /posts/[post ID here] back to plain old /posts. At least Google would stop emailing me.

Here’s how I did it:

You can match routes with regexes using constraint and passing in the id as a param. In your routes.rb:

get 'posts/:id', constraints: { id: /[0-9]+/ }, to: redirect('posts', status: 301)

And that's really all there is to it.