I am using Magento version 2.1.3 for my website.
We are getting the correct 404 page while accessing the non-existing url.
But I need to redirect the url to "/404" as well for the magento 404 page.
For Example:
I have accessed my website with "/abc" and getting 404 page but the url remains same as
www.domain.com/abc
I need to redirect the url to "/404" instead of getting the same url("/abc") what we have typed for every 404 Pages.
www.domain.com/abc should redirect to www.domain.com/404 if it is non existing url.
Please can any one suggest a best solution for this…
Please advise,
Sandra
Best Answer
You can do this by creating a module as follows.
Create a new module and add these files:
1)
Your\Module\Controller\NoRouteHandler.php
Here we are creating a new
NoRouteHandler
that will be used instead of the default Magento one that uses thecms/noroute/index
controller. We want to use a custom controller instead, in this case,404/redirect/index
.2)
Your/Module/etc/frontend/di.xml
This adds our handler to the
NoRouteHandlerList
collection, placing it before the default Magento one by using a sort order of 20.Now we need to declare a new route:
3)
Your\Module\etc\frontend\routes.xml
We need two controllers, the first controller is
4)
Your\Module\Controller\Redirect\Index.php
This controller redirects to the "/404" url which corresponds to our other controller shown below which simply forwards to the
cms\noroute\index
controller.5)
Your\Module\Controller\Index\Index.php
With this module in place, 404 pages will have the "/404" URL instead of whatever the user entered.