Cakephp 3.1 - How to redirect based on query strin

2020-05-09 07:33发布

问题:

We recently updated our site from pure php to cakephp 3 and having trouble redirecting urls that have params to a new url.

For example this redirect works fine

$routes->redirect('/webcast.php', '/webcast', ['status' => 302]);

But if there's parameters, it doesn't work

$routes->redirect('/webcast.php?id=100', '/webcast', ['status' => 302]);

Any ideas?

Thanks.

回答1:

The router doesn't support matching on query strings, the URL passed to the router when checking for a matching route won't have any query string values attached anymore.

While it would be possible to workaround this by using a custom routing dispatcher filter, a custom/extended Router class, and a custom/extended RouteCollection class, this seems like way too much work for something that can easily be defined as for example a rewrite rule on server level.

Apache mod_rewrite example:

RewriteCond %{QUERY_STRING} ^id=100$
RewriteRule ^webcast\.php$ /webcast? [L,R=302]

And note that 301 is usually the preferred redirect method.

See also

  • Apache > HTTP Server > Documentation > Version 2.4 > Apache mod_rewrite