New in Symfony 4.1: Smarter URL redirections
March 1, 2018 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
Contributed by
Nicolas Grekas
in #26283.
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 calledfoo
https://example.com/foo
is usually considered a file calledfoo
without any file extension.
Although serving different content for /foo
and /foo/
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 /foo/
.
Note that this only works for GET
and HEAD
requests.
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 404
response. In Symfony 4.1, it results in a 301
redirect to /foo
, making
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.