php - 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 检查?感谢您的耐心和时间。
解决方案
Wordpress 有一个添加斜杠的功能:
trailingslashit($string);
推荐阅读
- r - 如何根据抓取结果中的符号将 R 中的一列拆分为两列?
- sql - SQL 批量上传/复制格式文件错误
- vhdl - 使用 GHDL 使用 COE 文件模拟 Xilinx FIR 编译器
- ios - 为集合视图单元格转换 pdf 的第一页时创建黑框的代码。如何解决这个问题?
- azure - Azure Powershell:查找虚拟机的创建者
- python - Geopandas 空间连接失败 - 不支持的格式字符串
- react-native - React Native 是否有相对于字体的大小单位?
- pivot-table - 使用 DAX 计算涉及事实表上日期的度量
- ios - 有没有办法获取从文档目录生成并保存到 ibooks 或电子邮件的 pdf?
- javascript - 如何使用脚本应用程序在 Java 脚本中执行呼叫签名?