New in Symfony 4.1: Smarter URL redirections
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
Historically, URLs have followed the UNIX convention of adding trailing slashes for directories and removing them to refer to files:
https://example.com/foo/is usually considered a directory called
https://example.com/foois usually considered a file called
foowithout any file extension.
Although serving different content for
is OK for Google, nowadays it's common to treat both URLs as the same URL and
redirect between them.
Since day one Symfony has helped you in one of the two sides of this problem. If you define a route with a path ending with a slash, both URLs work and the one without slash redirects to the other one:
1 2 3 4
# config/routes.yaml foo_route: path: '/foo/' controller: App\Controller\DefaultController::foo
In this example, a
GET /foo/ request returns a
200 response and a
GET /foo request returns a
301 (Moved Permanently) redirect to
Note that this only works for
In Symfony 4.1 we improved the router to make smarter redirections in the other way too. Consider this route definition:
1 2 3 4
# config/routes.yaml foo_route: path: '/foo' controller: App\Controller\DefaultController::foo
Previously to Symfony 4.1, a
GET /foo/ request resulted in a
response. In Symfony 4.1, it results in a
301 redirect to
the trailing slash smart logic finally work both ways.
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
But why-not a 308 redirection? It allows to preserve the request body and method.