WordPress: How to do 301 redirects when the old URLs are index.php?variable=something

Posted by on Mar 6, 2015 in Featured, Tutorials

WordPress: How to do 301 redirects when the old URLs are index.php?variable=something

I recently had the opportunity to take over an old website for a client that was ranking pretty well for his targeted keywords. The old website was built using ModX, a CMS with which I’ve had limited experience. The developer of this site chose not to use mod rewrite to make search engine friendly (SEF) URLs, so all of the pages on the website ended with /index.php?id=123. If the website had used SEF URLs, I would have done my usual list of 301 redirects on the .htaccess file to properly forward users to pages on the new website. I quickly found out, that because of the way WordPress uses the index.php file, this way was not an option. It ends up causing an endless redirection loop as it redirects only the index.php of of the address and ignores the variable, so it essentially tries over and over to redirect to itself. I tried Googleing this one for a while, but getting meaningful results out of a search like “301 redirect wordpress index.php with variables” and other variations got me more confused than I was when I started. So, I figured I revert back to the two languages I know to see if either one could help. JavaScript offered some hope, but I’m not as strong with that as I am with PHP. I knew I would have to attack the problem as early as possible in the page serving process to keep things quick and SEO disruption to a minimum. If you’ve ever looked at the index.php file of a WordPress installation, you know that there’s not much to it. It basically points to the header.php file and the chain of events starts from there that make any given page of your website. I decided I would inject my code just before that process starts. First, I used $_GET to grab the variable from the URL and make a constant one of my own. Next, I use a series of if/then statements to assign different 301 redirects based on what the variable...

Read More »