Redirecting to the home page from within a Plug

I have a plug called Subdomain in charge of setting the subdomain private variable to the conn object, and also applying a custom secondary router called SubdomainRouter.

It work fine, however I’m trying to add a validation rule that if someone visits a subdomain for a team that doesn’t exist, I redirect them to the root page.

Does anyone know how to redirect from within a Plug?

def call(conn, router) do
    case get_subdomain(conn.host) do
      subdomain when byte_size(subdomain) > 0 ->
        case MyApp.TeamQueries.get_by_slug(subdomain) do
          nil ->
            conn
            |> Redirect to home somehow? https://localhost:4443
            |> halt
          team ->
            conn
            |> put_private(:subdomain, subdomain)
            |> router.call(router.init({}))
            |> halt
        end
      _ -> conn
    end
  end

I solved it this way:

conn
|> Phoenix.Controller.redirect(external: root_url(conn))
|> halt

...

defp root_url(conn) do
  host = conn.host # "foobar.localhost
    |> String.split(".")
    |> Enum.at(1)

  if conn.port do
    "#{conn.scheme}://#{host}:#{conn.port}"
  else
    "#{conn.scheme}://#{host}"
  end
end
2 Likes

Have you tried redirect/2?

I’m guessing you can do this:

conn
|> redirect(external: https://localhost:4443)
|> halt

Here we’re using external since to only accept paths.

EDIT: whoops, you’re faster than me :slight_smile: