ZF2 maintenance page

旧巷老猫 提交于 2019-12-06 11:43:30

问题


I try to set up a maintenance page with ZF2 but it's not working. I put a maintenance.html page in public folder (www) and in my onbootstrap function I've got the following code :

    $config = $e->getApplication()->getServiceManager()->get('Appli\Config'); 
    if($config['maintenance']) {
        $response  = $e->getResponse();
        $response->getHeaders()->addHeaderLine('Location', '/maintenance.html');
        $response->setStatusCode(503);
        return $response;
    }

I enter the if cause $config['maintenance'] is true but it's not displaying my maintenance.html page as expected. Instead it displays the page asked. Is there something wrong about my redirection ?


回答1:


You appear to be attempting to short-circuit the request directly from your onBootstrap method. That won't work, at that point the route hasn't been resolved and the controller hasn't been dispatched. Essentially, all you're doing is pre-populating the response, only for it to be over-written once the request is routed and dispatched.

If you want to affect the response, you'll need to listen to one of the other MvcEvents. It seems you want to do this before a controller is dispatched, so the place to do it would be in the EVENT_ROUTE, ideally with a high priority so it happens before the route is resolved by the router (saves wasted processing resolving a route that will never be dispatched).

public function onBootstrap(MvcEvent $e)
{
    $events = $e->getApplication()->getEventManager();
    $events->attach(MvcEvent::EVENT_ROUTE, function (MvcEvent $r) {
        $config = $r->getApplication()->getServiceManager()->get('Appli\Config');
        if ($config['maintenance']) {
            $response = $r->getResponse();
            // set content & status
            $response->setStatusCode(503);
            $response->setContent('<h1>Service Unavailable</h1>');
            // short-circuit request...
            return $response;
        }
    }, 1000);
}



回答2:


You can't set a 503 status code and redirect - the two are mutually exclusive, as redirects use a 3xx status code.

You probably want something more like:

$response->setContent(file_get_contents('/path/to/maintenance.html'));
$response->setStatusCode(503);


来源:https://stackoverflow.com/questions/23435610/zf2-maintenance-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!