首页 > 解决方案 > 使用 magento2 在 url 中添加斜杠

问题描述

如何在不使用 mod_rewrite 的情况下使用 magento2 添加没有指定文件(301 重定向)的 url 斜杠,仅在代码中。

标签: phpmagento

解决方案


应用程序/代码/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 页面)。

此致!


推荐阅读