I want user redirect to https insetad of http just after login in my new website made in zend framework2. please help.
I there any method available in zend freamework2 to get current used protocol(http or https).
I want user redirect to https insetad of http just after login in my new website made in zend framework2. please help.
I there any method available in zend freamework2 to get current used protocol(http or https).
You can redirect the user to the https version of a page inside the application. Above solution simply redirects all requests to it's http variant, and only for Apache. I would rather do it inside the application (then you're more in control) and make it server agnostic (what happens when you switch to nginx?)
An example is based on an answer I gave earlier here: ZF2 and force HTTPS for specific routes
The solution: create a controller plugin which you can call every time you need it. Specify the pages you need to force a redirect (i.e. the page you show the login form):
use Zend\Http\Response;
public function loginAction()
{
// If return value is response, this means the user will be redirected
$result = $this->forceHttps();
if ($result instanceof Response) {
return $result;
}
// code here
}
And then you could create a controller plugin (call it ForceHttps
) to return a response when the user should be redirected:
use Zend\Uri\Http as HttpUri;
class ForceHttps extends AbstractPlugin
{
public function __invoke()
{
$request = $this->getController()->getRequest();
if ('https' === $request->getUri()->getScheme()) {
return;
}
// Not secure, create full url
$plugin = $this->getController()->url();
$string = $plugin->fromRoute(null, array(), array(
'force_canonical' => true,
), true);
$url = new HttpUri($string);
$url->setScheme('https');
return $this->getController()->redirect()->toUrl($url);
}
}
What happens is
null
), force the canonical version (i.e. with a full scheme and domain name) and reuse the current route match parameters (the true
as last parameter).on your .htaccess
write these rules
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yoursite.com/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ public/index.php [NC,L]
note that public/index.php
is the root so you have to modify it and www.yoursite.com
too
for logged-in user
you have to do with php
$auth = Zend_Auth::getInstance();
if($auth->hasIdentity()) {//redirection should be here//}