1

I'd like to create some service that would be responsible for auto-redirecting some routes to secure version of the URL. For example:

http://domain.com/checkout -> https://secure.domain.com/checkout
http://domain.com/about // route not marked as secure, no redirection

I know I can partially achieve that with schema:

secure:
    path:     /secure
    defaults: { _controller: AcmeDemoBundle:Main:secure }
    schemes:  [https]

However I also need to change hosts. Should I hook up to some kernel events or something?

4

2 に答える 2

1

私が最終的に得たものは次のとおりです。

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ルーティング構成でオプションが設定されているかどうかを確認し、そうであれば、それが安全な接続上にあるかどうかを確認します-そうでない場合は、安全なドメインにリダイレクトします。

于 2013-09-09T12:47:59.510 に答える