8
votes

Is there any way to insert a Plug to run prior to the router selecting the controller/action? I've got an app that will redirect to the root path for specific subdomains, regardless of the current path on those domains. So:

sub.myapp.com/foo/bar should redirect to sub.myapp.com/

But, by default, the Router says there is no path for /foo/bar and it halts execution of my plugs, meaning it never hits my redirect.

Is there a way to insert my plug prior to the Router choosing the action/controller?

(Note: I'm pretty sure I can handle this case with a catch-all route, but I'm just curious if there's a better way.)

1

1 Answers

11
votes

Your router is called explicitly in lib/my_app/endpoint.ex. You can add any plugs you like in that file before then.

You can write a plug that handles the redirects and halt the connection before the router is called.

defmodule HelloPhoenix.Endpoint do
  use Phoenix.Endpoint, otp_app: :hello_phoenix
  plug Plug.RequestId
  plug Plug.Logger
  ...
  plug CustomRedirectPlug # Add your plug here
  plug HelloPhoenix.Router
end