polak polkovski
polak polkovski

Reputation: 97

Add trailing slash into url with magento2

how can I add trailing slash of url without specified file (301 redirect) with magento2 without using mod_rewrite, only in code.

Upvotes: 1

Views: 1833

Answers (1)

magento4u_com
magento4u_com

Reputation: 364

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!

Upvotes: 1

Related Questions