Magento 2 Redirect to 404 from Controller

There are many times a Magento 2 controller should be forwarded to a 404 (noroute) path – making a GET request for a path that should only respond to a POST request, a dynamic controller that allows some but not all paths, etc. This sounds simple, right? It is, but for some reason I always forget the proper syntax and spend way too long looking it up… Hopefully this post can save you some time like I feel it will for me.

How to forward a request to a 404 page from a Magento 2 controller

The Magento 2 router can be used to forward any request to another action/controller as needed. In the case of this tutorial, the request needs to be forwarded to what Magento calls the noroute action. The noroute action will set the header Status Code to 404 (not found). The configured Magento 404 page will be returned to the visitor.

Use Magento ResultFactory to Redirect to noroute

The Magento framework class of Magento\Framework\Controller\ResultFactory [source] is used to forward to the noroute action. This handles setting the proper headers and obtaining the proper 404 page content from Magento.

Controller Example

Here’s a very simplified example controller that checks if the request has POST data. If it does, process the controller logic. If not, return a 404 (or noroute as Magento calls it) response.