Phoenix - redirects in router file

It would be nice to be able to define a redirect from one route to another from the router.ex file. E.g.:

redirect "/", UserController, :list
get "/users", UserController, :list

This is typically needed when you have a URL that you want the user to be able to type but that should be redirected to a more specific URL.

Ofc I can code an action and a redirect myself, but such a helper would avoid me to add that code that could be explicitly defined in the router; you can then quickly see that there is a redirect along with the other routes, without inspecting the controller’s code. I think such redirects without any logic belongs there.

What do you think about that idea?

I think this is a good idea, if a little niche. although you’d want to implement it as redirect "/", "/users" because redirect "/", UserController, :list is ambiguous. Multiple paths can route to the same controller action.

3 Likes

Phoenix.Controller.redirect/2 is a plug, and the generated router for phoenix has it imported by default. Together with forward you should be able to use it already without the need for additional code.

1 Like

One command that i find very useful when dealing with routes is mix phx.routes it shows you what routes you have.

Also have a look at this https://hexdocs.pm/phoenix/controllers.html#redirection it should show you how to redirect with different options.

Hope that it helps

We ran into this on the project I’m working on. We found this blog post to be a pretty good way to do this: https://www.viget.com/articles/how-to-redirect-from-the-phoenix-router/

We ended up with a plug that lets us do this:

get "/", Redirect, to: "/datasets"

You can see our implementation here: https://github.com/smartcitiesdata/smartcitiesdata/blob/master/apps/andi/lib/andi_web/plugs/redirect.ex
https://github.com/smartcitiesdata/smartcitiesdata/blob/master/apps/andi/lib/andi_web/router.ex

It looks like there is a plug_redirect package in Hex that does adds a redirect keyword. Their Readme suggests using it as its own Plug in your endpoint, but at a quick glance I don’t see any reason you couldn’t use it in a Phoenix router

2 Likes

The redirect library addresses this shortcoming by providing with a redirect/3 macro, allowing to redirect a request from one path to another in the router.exfile:

redirect "/", "/users", :permanent # 301 redirect
redirect "/", "/users", :temporary # 302 redirect

â €

1 Like