Replacing changed directory names with .htaccess

After poking around with some Rewrite rules and nearly losing my nerve with what seemed to be a choice between a 500 Internal Error and WordPress’ 404 pages, I finally came up with a redirect instruction for my .htaccess file that replaces a subdirectory name in URLs which end in .html.

I need this because when I started marginaali, I used Blogger which outputs html files. I then moved on to WordPress and imported everything I had blogged thus far – apart from the comments that I had received. Therefore I didn’t have the heart to delete all those .html files and was sort of stuck between the two.

After activating pretty permalinks, all requests to those old posts were redirected to the WordPress ones, and so the comments were, in effect, not available. Not until I changed the old posts’ directory name from both Blogger’s and WordPress’ standard naming by the year, by prefixing the (thankfully only) 2004 directory with an ‘o’, into ‘o2004’.

There was one additional problem: that of old links out there in the Net pointing to these old posts and the comments in them – they were now broken of course. Here’s where I figured a relatively simple rewrite rule should do the trick: in all requests to files ending in .html under /marginaali/, replace the 2004 with the o2004.

Well, like I implied in the beginning, this was surprisingly difficult to achieve with my little experience in tweaking .htaccess files. I finally succeeded, however, and here’s my solution:

RedirectMatch /marginaali/2004/(.*)\.html$$1.html

I placed this directive after the segment added by WordPress, in the the same .htaccess file that controls the permalinking, in /marginaali/. It leaves requests to the WP versions of posts (such as this one) intact, while fixing the requests to their html versions with the added ‘o’ so that, for example, 2004/11/sepe.html gets redirected to o2004/11/sepe.html. (That is an actual example of a page being referred to out on someone else’s page, which I have no control over.)