Skip to content

How to Configure a Redirect without a custom Controller

Warning: You are browsing the documentation for Symfony 2.x, which is no longer maintained.

Read the updated version of this page for Symfony 7.1 (the current stable version).

Sometimes, a URL needs to redirect to another URL. You can do that by creating a new controller action whose only task is to redirect, but using the RedirectController of the FrameworkBundle is even easier.

You can redirect to a specific path (e.g. /about) or to a specific route using its name (e.g. homepage).

Redirecting Using a Path

Assume there is no default controller for the / path of your application and you want to redirect these requests to /app. You will need to use the urlRedirectAction() action to redirect to this new url:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# app/config/routing.yml

# load some routes - one should ultimately have the path "/app"
AppBundle:
    resource: '@AppBundle/Controller/'
    type:     annotation
    prefix:   /app

# redirecting the root
root:
    path: /
    defaults:
        _controller: FrameworkBundle:Redirect:urlRedirect
        path: /app
        permanent: true

In this example, you configured a route for the / path and let the RedirectController redirect it to /app. The permanent switch tells the action to issue a 301 HTTP status code instead of the default 302 HTTP status code.

Redirecting Using a Route

Assume you are migrating your website from WordPress to Symfony, you want to redirect /wp-admin to the route sonata_admin_dashboard. You don't know the path, only the route name. This can be achieved using the redirectAction() action:

1
2
3
4
5
6
7
8
9
10
11
# app/config/routing.yml

# ...

# redirecting the admin home
root:
    path: /wp-admin
    defaults:
        _controller: FrameworkBundle:Redirect:redirect
        route: sonata_admin_dashboard
        permanent: true

Caution

Because you are redirecting to a route instead of a path, the required option is called route in the redirect() action, instead of path in the urlRedirect() action.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version