简体   繁体   中英

How can i redirect to a HTTP page from HTTPS page in ZF2?

I have applied https redirection on number of pages but whenever i go on another route through ZF2 redirect, next page opens with https. I want to apply https only on selected pages. Please suggest..??

After searching alot i found the solution. Just update you app's Module.php as follows :

public function onBootstrap(MvcEvent $e)
{
    $eventManager = $e->getApplication()->getEventManager();

    $moduleRouteListener = new ModuleRouteListener();
    $moduleRouteListener->attach($eventManager);


    $eventManager->attach('route', array($this, 'doHttpsRedirect'));

    // your code
}

and add the function doHttpsRedirect like :

    public function doHttpsRedirect(MvcEvent $e)
    {
        $sm = $e->getApplication()->getServiceManager();
        $uri = $e->getRequest()->getUri();
        $controller = $e->getRouteMatch()->getParam('controller');
        $action =  $e->getRouteMatch()->getParam('action');
        $securedPages = array('Application\Controller\Login', 'Application\Controller\Register', 'Application\Controller\shopping');

        if (in_array($controller, $securedPages)) {
            $scheme = $uri->getScheme();
            if ($scheme != 'https') {
                $uri->setScheme('https');
                $response = $e->getResponse();
                $response->getHeaders()->addHeaderLine('Location', $uri);
                $response->setStatusCode(302);
                $response->sendHeaders();
                return $response;
            }
        } else if (!in_array($controller, $securedPages)) {
            if ($_SERVER["HTTPS"] == "on") {
                $uri->setScheme('http');
                $response = $e->getResponse();
                $response->getHeaders()->addHeaderLine('Location', $uri);
                $response->setStatusCode(302);
                $response->sendHeaders();
                return $response;
            }
        }
    }

That's all..!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM