php - 使用 magento2 在 url 中添加斜杠
问题描述
如何在不使用 mod_rewrite 的情况下使用 magento2 添加没有指定文件(301 重定向)的 url 斜杠,仅在代码中。
解决方案
应用程序/代码/your_vendor/your_module/etc/frontend/events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_predispatch_cms_index_index">
<observer name="unique_name" instance="your_vendor\your_module\Observer\CustomPredispatch" />
</event>
</config>
app/code/your_vendor/your_module/Observer/CustomPredispatch.php
<?php
namespace your_vendor\your_module\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
class CustomPredispatch implements ObserverInterface
{
public function execute(Observer $observer)
{
$request = $observer->getEvent()->getRequest();
if(substr($request->getRequestUri(), -1) !== '/'){
$observer->getEvent()->getControllerAction()->getResponse()->setRedirect($request->getRequestUri() . '/', 301)->sendResponse();
}
}
}
这将适用于主页(包括将商店代码添加到网址)。
如果您希望它适用于所有请求,则应将 controller_action_predispatch_cms_index_index 更改为仅 controller_action_predispatch。
同样,如果您希望它适用于特定的路由/控制器/操作,则必须相应地替换 cms_index_index。
例如,要将其与所有 cms 页面一起使用,请将 controller_action_predispatch_cms_index_index 更改为 controller_action_predispatch_cms_page_view 或只是 controller_action_predispatch_cms(用于主页 + 其他 cms 页面)。
此致!
推荐阅读
- python - 如何在递归函数中保持值不变?
- google-cloud-platform - CloudRun 正在超过最大实例数(共 1 个)
- go - 使用等待组的 Golang 工作者
- javascript - 如何添加不与更新内容功能冲突的自动图像幻灯片放映
- python - pd.DataFrame 上的 for 循环继续运行,但在 100 次迭代后停止工作
- php - 如何插入或更新来自不同表的记录
- arrays - C char 数组在赋值循环后丢失指针
- azure-data-factory - Azure 数据工厂 - 不安然后删除
- c# - 如何在 C# 中使用 sendgrid 添加回复
- python - 我喜欢从双重列表中消除重复的组件,然后合并双重列表