24 Mar 2013, 21:46

How to change your WordPress permalink structure without losing old links

I recently realized that when I changed my WordPress permalink structure from /%year%/%month%/%day%/%title/ to just /%title%/ that I had some old links floating around on various websites like StackOverflow. While normally I wouldn’t care too terribly much, one in particular was quite popular which I can only assume and hope meant that it was particularly helpful. I didn’t want that to be lost to the community.

To address this, I added a new location directive with a rewrite rule to my nginx config, like so:

# For locations matching /0000/00/00/some-title-of-a-post
location ~ "^/[0-9]{4}/[0-9]{2}/[0-9]{2}/([a-z0-9\-/]+)" {
     # Store the post title in a variable, because the rewrite resets the backreferences from the regular expression
     set $post_title $1;
     # Use the stored title to rewrite the address
     rewrite ^(.*)$ http://blog.sdbarker.com/$post_title permanent;

This allowed me to not break any old WordPress permalinks that were floating around while keeping the new, current style.

Both links now work as expected. Unforunately, though, the poor StackOverflow visitors who needed the help that article provided will not be able to find it. The StackOverflow moderators oh so very helpfully deleted not only the original answer that contained the link, but all three of my attempts to re-answer the question. And all without any explanation. Awesome.