1

I have a website where I need to 301 redirect all old pages that are incoming from old URLs like /?page_id=261, /?page_id=204, /?page_id=2677 and so on to the main home page.

What would be a proper way of doing it? Will something like this in .htaccess work? I do not want to redirect all 404's - just these type of old links.

RedirectMatch 301 ^/?page_id=4&n=$1 https://www.example.com/
1
  • What's the &n=$1 supposed to be referring to in your example code? There's no mention of this in your example URLs. – MrWhite May 31 '19 at 14:06
3

You can't match the query string using a mod_alias RedirectMatch directive. This directive matches against the URL-path only. You need to use mod_rewrite instead, with a condition that checks the QUERY_STRING server variable.

For example, at the top of your .htaccess file, try the following:

RewriteCond %{QUERY_STRING} ^page_id=\d+$
RewriteRule ^$ / [QSD,R=302,L]

The QSD flag (Apache 2.4) is required to remove the query string from the target URL.

However, from an SEO perspective, mass redirections like this will likely be seen as soft-404s by the search engines. You should try to redirect on a per page basis to the new URL. If the content no longer exists then return a 404.

1
  • Thanks this worked for me – twelvell Jun 2 '19 at 12:05
2

If you want to do it in a WordPressy way, the action hooks are the way to do so. Here's a self explanatory piece of code that will do the trick:

// We hook into the template_redirect action hook, which is the proper
// hook to be used for redirections
add_action('template_redirect','wpse339255_redirect_old_urls');

/**
 * Check whether the page_id query string has been set,
 * and if so, redirect the user to homepage
 */
function wpse339255_redirect_old_urls(){
    // Check if the page_id query string is set
    if( isset( $_GET['page_id'] ) && ! empty( $_GET['page_id'] ) ){
        // Do the redirect
        wp_redirect( home_url() );
        die;
    }

}
1
  • Yes, this is also working fine. Thanks – twelvell Jun 3 '19 at 18:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.