我最终得到的是:
1)我在路由(https
)中设置了一个自定义选项:
acme_dynamic:
pattern: /
options:
https: true
defaults:
_controller: acmeCommonBundle:Default:dynamic
2)我为kernel.response
事件创建了一个监听器:
namespace acme\CommonBundle\EventListener;
use acme\CommonBundle\Controller\HttpsController;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
class HttpsControllerListener
{
/**
* Base HTTPS Url
* @var string
*/
private $httpsUrl;
/**
* Request
* @var [type]
*/
private $request;
/**
* [$router description]
* @var [type]
*/
private $router;
public function __construct($httpsUrl, $request, $router)
{
$this->httpsUrl = $httpsUrl;
$this->router = $router;
$this->request = $request;
}
public function onKernelResponse(FilterResponseEvent $event)
{
$routeCollection = $this->router->getRouteCollection();
$route = $routeCollection->get($this->request->get('_route'));
if ($route and $route->getOption('https') === true and $this->request->server->get('HTTPS')) {
$response = $event->getResponse();
$event->setResponse(new RedirectResponse($this->httpsUrl . $this->request->server->get('REQUEST_URI')));
}
}
}
3)我已将其注册到上述事件:
acme.https_controller_listener:
class: acme\CommonBundle\EventListener\HttpsControllerListener
arguments: [%baseurl.https%, @request, @router]
scope: request
tags:
- { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }
基本上它拦截响应,检查当前路由是否https
在路由配置中设置了选项,如果有,检查它是否在安全连接上 - 如果没有,则重定向到安全域。