Redirect and Alias

Redirect

Redirecting is also done in the routes configuration. To redirect from /a to /b:

  1. const routes = [{ path: '/home', redirect: '/' }]

The redirect can also be targeting a named route:

  1. const routes = [{ path: '/home', redirect: { name: 'homepage' } }]

Or even use a function for dynamic redirecting:

  1. const routes = [
  2. {
  3. // /search/screens -> /search?q=screens
  4. path: '/search/:searchText',
  5. redirect: to => {
  6. // the function receives the target route as the argument
  7. // we return a redirect path/location here.
  8. return { path: '/search', query: { q: to.params.searchText } }
  9. },
  10. },
  11. {
  12. path: '/search',
  13. // ...
  14. },
  15. ]

Note that Navigation Guards are not applied on the route that redirects, only on its target. e.g. In the example below, adding a beforeEnter guard to the /home route would not have any effect.

When writing a redirect, you can omit the component option because it is never directly reached so there is no component to render. The only exception are nested routes: if a route record has children and a redirect property, it should also have a component property.

Relative redirecting

It’s also possible to redirect to a relative location:

  1. const routes = [
  2. {
  3. path: '/users/:id/posts',
  4. redirect: to => {
  5. // the function receives the target route as the argument
  6. // return redirect path/location here.
  7. },
  8. },
  9. ]

Alias

A redirect means when the user visits /home, the URL will be replaced by /, and then matched as /. But what is an alias?

An alias of / as /home means when the user visits /home, the URL remains /home, but it will be matched as if the user is visiting /.

The above can be expressed in the route configuration as:

  1. const routes = [{ path: '/', component: Homepage, alias: '/home' }]

An alias gives you the freedom to map a UI structure to an arbitrary URL, instead of being constrained by the configuration’s nesting structure. Make the alias start with a / to make the path absolute in nested routes. You can even combine both and provide multiple aliases with an array:

  1. const routes = [
  2. {
  3. path: '/users',
  4. component: UsersLayout,
  5. children: [
  6. // this will render the UserList for these 3 URLs
  7. // - /users
  8. // - /users/list
  9. // - /people
  10. { path: '', component: UserList, alias: ['/people', 'list'] },
  11. ],
  12. },
  13. ]

If your route has parameters, make sure to include them in any absolute alias:

  1. const routes = [
  2. {
  3. path: '/users/:id',
  4. component: UsersByIdLayout,
  5. children: [
  6. // this will render the UserDetails for these 3 URLs
  7. // - /users/24
  8. // - /users/24/profile
  9. // - /24
  10. { path: 'profile', component: UserDetails, alias: ['/:id', ''] },
  11. ],
  12. },
  13. ]

Note about SEO: when using aliases, make sure to define canonical links.