Symfony News

New in Symfony 4.1: Smarter URL redirections

Nicolas Grekas

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 called foo
  • https://example.com/foo is usually considered a file called foo 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/. 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.


Be trained by Symfony experts - 2018-03-12 Cologne - 2018-03-19 Clichy - 2018-03-19 Clichy


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook