简体   繁体   中英

Add trailing slash into url with magento2

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

app/code/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();
        }
    }

}

This will work for the homepage (including Add Store Code to Urls).

If you want it to work for all requests, you should change controller_action_predispatch_cms_index_index into just controller_action_predispatch.

Similarly if you want it to work for specific route/controller/action you have to replace cms_index_index accordingly.

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).

Best regards!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM