首页 > 解决方案 > PHP签入一个函数以将非斜杠URL重定向到斜杠URL

问题描述

我有一个控制分页 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();

     }
 }

如何在调用我必须强制使用尾随斜杠的 htaccess 规则的情况下,从非尾随斜杠 URL 直接到尾随斜杠实现这个PHP 检查?感谢您的耐心和时间。

标签: phpwordpress.htaccessredirect

解决方案


Wordpress 有一个添加斜杠的功能:

trailingslashit($string);

推荐阅读