During an SEO audit, we decided to update the permalinks in our blog to include the blog slug. This apparently lets the Google know that the content lives in the blog section of the site and doesn’t compete as much with actual top-level pages. Previously, we have all our blog posts set to show as top level urls. Working again on setting up the htaccess redirects for the brown bag site.
Updating the setting in WordPress is simple enough (see above), but there’s also the task of setting up redirects for all the old blog post urls, that turn up as 404s as soon as you save that permalink structure update. So there are around one hundred blog posts and any incoming link to them would be broken (links on the site work fine since they are loaded with the new permalink settings). Thus we get to play with the htaccess file and write some 301 redirect rules. Since there is nothing we can use to match all the existing post urls, we have to write a rule for each post. Not too bad, so we created the list of old vs new urls and added them. But in our testing, it gave us some issues since some links to our posts have a trailing backslash and some do not. The quick lazy fix was to add another hundred rules to our htaccess file and call it a day, but we didn’t want two redirect rules for every post. We started here (x100):
Redirect 301 /boomerangers-baggers-say-what/ https://www.brownbagmarketing.com/blog/boomerangers-baggers-say-what/
Which was just matching with the slash. We tried some regex combinations, but that didn’t seem to work. So, I ended up reading the manual and rediscovered RedirectMatch.
For more complex matching using regular expressions, see the RedirectMatch directive.
And here’s what I got to work finally:
RedirectMatch 301 ^/boomerangers-baggers-say-what/?$ https://www.brownbagmarketing.com/blog/boomerangers-baggers-say-what/
^ to make it match from the beginning of the string (so it doesn’t get into an infinite loop)
? to make the trailing slash optional
$ to make it match the end of the string (so it doesn’t match other urls that may be similar but not exact)
So now our blog urls are more SEO friendly and the old incoming links will safely arrive at their destination. And we have 100 redirect rules (the minimum we could since there are no other match rules that would work with our top level post urls that wouldn’t also match every/any other page of the site) to show for it, rather than 200.
Side note: I also found a good tool too (regexr.com), it’s more useful than my previous regex goto (regex101.com). It does a better job at teaching the innards of the expressions. It’s also nice how you can save your regex for later, see ours: http://regexr.com/3bvtf.