简体   繁体   中英

How to redirect without GET parameters using the routing?

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 ?

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);
}

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