ZF2 maintenance page

2019-04-14 02:50发布

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 ?

2条回答
女痞
2楼-- · 2019-04-14 03:12

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);
}
查看更多
老娘就宠你
3楼-- · 2019-04-14 03:16

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);
查看更多
登录 后发表回答