404 to 301 – Fixing old links

I have currently updated a site and made many improvements to it. The old site ran off 3 different systems and had wordpress (and the other systems) in the webroot. I have moved wordpress into a subdirectory (wordpress) and I also updated my blog posts to be prefixed with blog/. Pages and the front page are not prefixed with blog/.

The issue I am having is that I want to gracefully tell Google and other search engines that these posts are now prefixed with /blog/.

Read More

I used the following code in my 404 page before I realized that wordpress throws a 404 header. Obviously, this is not the correct way to implement this fix.

// Check if old site URL and redirect if so
if (substr($s, 0, 8) != 'reviews/') {
    if (substr($s, 0, 5) != 'blog/' && substr($s, 0, 10) != 'wordpress/' ) {
        // Force our 301 redirect so we can keep the new URI: /blog/
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: /blog/{$s}");
        exit();
    }
}

What I need to do is find out when wordpress knows this is a 404 and see if it matches my checks (currently what is in the snippet above) and if a match occurs force a 301 redirect to update the crawlers.

I am not sure if this information is available on init, as this is my next step to test.

I tried playing with template_redirect and redirect_canonical but they don’t seem to be the correct methods to attach to.

Any help on this is appreciated. I am still trying to find a solution and will post back when I find one.

Thanks in advance.

Related posts

Leave a Reply

1 comment

  1. If you intend to do checks based on template tags you should hook on wp action. template_redirect will suffice too, but wp is earlier. This is when WP handles 404 itself.
    To perform a 301 redirect use status_header( 301 );, wp_safe_redirect(); immediately followed by exit;

    You could use a plugin handle these for you. It’s bit tricky to set-up if you are not that technical. Good luck.