Skip to content

how does magento 2 handle url redirects

ProcessEight edited this page Jan 19, 2021 · 1 revision

How does Magento 2 handle URL redirects?

    /**
     * Perform action and generate response
     *
     * @param RequestInterface $request
     * @return ResponseInterface|\Magento\Framework\Controller\ResultInterface
     * @throws \LogicException
     */
    public function dispatch(RequestInterface $request)
    {
        \Magento\Framework\Profiler::start('routers_match');
        $routingCycleCounter = 0;
        $result = null;
        while (!$request->isDispatched() && $routingCycleCounter++ < 100) {
            /** @var \Magento\Framework\App\RouterInterface $router */
/* 1 */     foreach ($this->_routerList as $router) {
                try {
/* 2 */             $actionInstance = $router->match($request);
                    if ($actionInstance) {
                        $request->setDispatched(true);
                        $this->response->setNoCacheHeaders();
                        if ($actionInstance instanceof \Magento\Framework\App\Action\AbstractAction) {
/* 7 */                     $result = $actionInstance->dispatch($request);
                        } else {
                            $result = $actionInstance->execute();
                        }
/* 8 */                 break;
                    }
                } catch (\Magento\Framework\Exception\NotFoundException $e) {
                    // ... Not relevant to our discussion
                }
            }
        }
        // ... Not relevant to our discussion
/* 9 */ return $result;
    }
  1. \Magento\Framework\App\FrontController::dispatch method passes the \Magento\Framework\App\RequestInterface request object () to each routers' match method.
  2. One of these routers is \Magento\UrlRewrite\Controller\Router and the request is passed to its' match method.
  3. That calls \Magento\UrlRewrite\Controller\Router::getRewrite, which attempts to load a matching URL rewrite from the database.
  4. If the rewrite is a 3xx type redirect, then the request from the FrontController and the rewrite object are both passed to \Magento\UrlRewrite\Controller\Router::processRedirect.
  5. processRedirect then generates the target URL for the redirect
  6. \Magento\UrlRewrite\Controller\Router::redirect sets the new URL to the response object and returns a new instance of the \Magento\Framework\App\Action\Redirect class
  7. Back in \Magento\Framework\App\FrontController::dispatch, the actionInstance variable is now set to \Magento\Framework\App\Action\Redirect and this instance of an action controller class is dispatched or executed (based on its inheritance tree - this is a backwards compatibility thing).
  8. An instance of \Magento\Framework\App\ResponseInterface is returned, we break out of the $this->_routerList loop and return the result object.
  9. Finally we return the result object with the output from our redirected URL.