[英]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();
}
}
}
This will work for the homepage (including Add Store Code to Urls). 这将适用于主页(包括将商店代码添加到Urls)。
If you want it to work for all requests, you should change controller_action_predispatch_cms_index_index into just controller_action_predispatch. 如果希望它适用于所有请求,则应将controller_action_predispatch_cms_index_index更改为controller_action_predispatch。
Similarly if you want it to work for specific route/controller/action you have to replace cms_index_index accordingly. 同样,如果您希望它适用于特定的路由/控制器/操作,则必须相应地替换cms_index_index。
For example to work it with all cms pages, change controller_action_predispatch_cms_index_index into controller_action_predispatch_cms_page_view or just controller_action_predispatch_cms (for homepage + other cms pages). 例如,要在所有cms页面上使用它,请将controller_action_predispatch_cms_index_index更改为controller_action_predispatch_cms_page_view或仅将controller_action_predispatch_cms更改为首页和其他cms页面。
Best regards! 最好的祝福!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.