i've a function that control paginated Wordpress content and redirect numbered URLs to its parent URL.
The function is working perfectly but i want that the redirect 301 for numbered URLs that don't have a final trailing slash, fires directly to the trailing slash URL. For example:
https://www.example.com/how-to-do-something/1111
should redirect immediately to
https://www.example.com/how-to-do-something/
At the moment, instead the redirect 301 is working but pass for https://www.example.com/how-to-do-something
and then to https://www.example.com/how-to-do-something/
.
But, at the same time, this check should not invalidate the numbered URLs with final trailing slash, that are already good, for example:
https://www.example.com/how-to-do-something/1111/
redirect perfectly to https://www.example.com/how-to-do-something/
in one shot. So there is to do nothing for those.
the function is the following:
global $posts, $numpages;
$request_uri = $_SERVER['REQUEST_URI'];
$result = preg_match('%\/(\d)+(\/)?$%', $request_uri, $matches);
$ordinal = $result ? intval($matches[1]) : FALSE;
if(is_numeric($ordinal)) {
// a numbered page was requested: validate it
// look-ahead: initialises the global $numpages
setup_postdata($posts[0]); // yes, hack
$redirect_to = isset($ordinal) ? '/': (($ordinal > $numpages) ? "/$numpages/" : FALSE);
if(is_string($redirect_to)) {
// we got us a phantom
$redirect_url = get_option('home') . preg_replace('%'.$matches[0].'%', $redirect_to, $request_uri);
// redirect to it's parent 301
header($_SERVER['SERVER_PROTOCOL'] . ' 301 Moved Permanently');
header("Location: $redirect_url");
exit();
}
}
How can i achieve this PHP check from non-trailing slash URL directly to trailing slash without invoke the htaccess rule that i have to force the trailing slash? Thanks for your patience and time.