【发布时间】:2019-04-07 22:25:44
【问题描述】:
我有一个函数可以控制分页的 Wordpress 内容并将编号 URL 重定向到其父 URL。
该功能运行良好,但我希望没有最终尾随斜杠的编号 URL 的重定向 301 直接触发到尾随斜杠 URL。例如:
https://www.example.com/how-to-do-something/1111
应该立即重定向到
https://www.example.com/how-to-do-something/
目前,重定向 301 正在工作,但传递给 https://www.example.com/how-to-do-something,然后传递给 https://www.example.com/how-to-do-something/。
但是,同时,此检查不应使带有最后斜杠的编号 URL 无效,这已经很好,例如:
https://www.example.com/how-to-do-something/1111/ 一次性完美重定向到https://www.example.com/how-to-do-something/。所以没有什么可以为他们做的。
函数如下:
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();
}
}
我怎样才能实现这个 PHP 检查 从非尾随斜杠 URL 直接到尾随斜杠 没有 调用我必须强制使用斜杠的 htaccess 规则?感谢您的耐心和时间。
【问题讨论】:
标签: php wordpress .htaccess redirect