ZF2 Controller Specific 404 Not Found Page

As we all know, Zend Framework 2 handles 404 not found event, so whenever you set HttpResponse’s status code in a controller with

$response = $this->getResponse();

ZF2, by default, intercepts the request and prints the default 404 page. For SEO purposes we should use wisely the status codes. At Instela, when a user types a mispelled word or tries to reach a removed page, we show similar results rather than the default 404 page but also for search engine spiders we give 404 status code at the background. (A mispelling example: https://tr.instela.com/cagatay-gurtrk–9306406) This is the right way to handle status codes but as I said before ZF2 does not allow us to do it by default.

I asked this question on Stackoverflow but I did not receive any satisfying answer. Then I came up with this idea to solve this problem. The idea here is on bootstrap event check in which controller we are (in our case “Title”) and if the check is true, iterating over attached event handlers and detach a specific one, in this case “Zend\Mvc\View\RouteNotFoundStrategy”.

In Module.php

Easy, right?

Software Development Manager @ebay, and Founder of @instelacom. Author of Building Serverless Architectures and AWS Certified Solutions Architect.