[英]Add trailing slash into url with magento2
如何僅使用代碼在不使用mod_rewrite的情況下使用magento2添加不帶指定文件(301重定向)的url尾部斜杠。
<?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>
<?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();
}
}
}
這將適用於主頁(包括將商店代碼添加到Urls)。
如果希望它適用於所有請求,則應將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頁面。
最好的祝福!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.