Apache RewriteRule for Changing Your Permalink Settings

I recently updated my blog’s permalink settings and did away with the year and month in the url structure. I’m experimenting with placing the post name more prominently in the url as it is better for SEO.
Here’s the Apache rewrite rule I used to move my blog posts from /yyyy/mm/post-name to /post-name. The rewrite rule uses a 301 redirect so this should not negatively affect the post’s Google rankings.

# Redirect moved blog posts
RewriteBase /blog/
RewriteRule ^20[0-1][0-9]/[0-9][0-9]/(.*) $1 [R=301,L]

Breaking the RegEx apart:

RewriteBase /blog/
This tells the rewrite engine that we are only going to look at URLs that are under the /blog/ directory

Since we indicated our RewriteBase is “/blog/” on the previous line, “/blog/” will be chopped off of the URLs;
“^” says that our string should now start with the following pattern
I started this blog in 2009, so I only need to target years after 2000. I started my year RegEx with “20” to simplify.
“[0-1]” indicates I’m looking for a number range between zero and one. Since I only need to target between 2009-2013 the next digit could only be a zero or 1.
“[0-9]” indicates that the last digit in the year could be any of these.
“/” the next character should be a forward slash

This RegEx targets the months: any digit zero through nine, followed by any digit zero through nine
“/” the next character should be a forward slash

The rest of the url is our post-name. “(.*)” says take the rest of the url string and remember it as the first variable.

 $1 [R=301,L]
“$1” is the first variable that we got from the (.*) statement above. “R=301” says to 301 redirect this request to whatever url is in the $1 variable. It knows to prepend ‘/blog/’ to the request because we indicated our URLs should start with “/blog/” using the RewriteBase command. “L” indicates that this should be the Last rewrite rule it processes.

Regex can be confusing. Its is often easiest to build up your RegEx bit by bit until you have the completed statement.

Leave a Reply

Your email address will not be published. Required fields are marked *