4

My routing is defined like this :

# New URLs
article_show:
    pattern:  /article/{id}
    defaults: { _controller: AcmeDemoBundle:Article:show }

# Old URLs
article_show_legacy:
    path:            /article-{id}-{param}.html
    requirements:
        param: foo|bar
    defaults:
        _controller: FrameworkBundle:Redirect:redirect
        route:       article_show
        permanent:   true

I'd like to know how I can redirect article_show_legacy to article_show without param parameter. At the moment whenever I access /article-1-foo.html (for example), I'm redirected to /article/1?param=foo. I would like to discard ?param=foo so I'm redirected to /article/1.

I know I can create one route for foo and one route for bar but in my case there's more cases.

Do I have to write my own redirect controller ?

iamdto
  • 1,372
  • 11
  • 23
  • I normally handle this s business logic in my controllers or twigs, Are you wanting a config-only type solution or should I post that type of response? – Lighthart Apr 03 '13 at 13:33
  • I know I can handle that in a controller, but I wondered if the routing component provided something to handle this automatically. – iamdto Apr 03 '13 at 13:49

1 Answers1

1

You have to write your own redirect controller or just create redirect method in any existing controller.

Check redirect action of the RedirectController in ../vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php for mor details.

Some example (I added third option stripAttributes):

public function redirectAction($route, $permanent = false, $stripAttributes = false)
{
    if ('' == $route) {
        return new Response(null, $permanent ? 410 : 404);
    }

    $attributes = array();
    if (!$stripAttributes) {
        $attributes = $this->container->get('request')->attributes->get('_route_params');
        unset($attributes['route'], 
              $attributes['permanent'], 
              $attributes['stripAttributes']);
    }

    return new RedirectResponse($this->container->get('router')->generate($route, $attributes, UrlGeneratorInterface::ABSOLUTE_URL), $permanent ? 301 : 302);
}
Vadim Ashikhman
  • 9,851
  • 1
  • 35
  • 39