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 /
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/
Share
Improve this question
edited May 31, 2019 at 14:32
MrWhite
3,8911 gold badge20 silver badges23 bronze badges
asked May 31, 2019 at 13:21
twelvelltwelvell
4114 silver badges13 bronze badges
1
|
2 Answers
Reset to default 4You 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.
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;
}
}
&n=$1
supposed to be referring to in your example code? There's no mention of this in your example URLs. – MrWhite Commented May 31, 2019 at 14:06