URL Redirect

Is there a way I can do a redirection to a new external url inside an Elixir route?

Thanks.

1 Like

If you are using Plug, you can use conn |> Plug.Conn.put_status(:found) |> Plug.Conn.put_resp_header("location", remote_url)

If you are using Phoenix, you can use Phoenix.Controller.redirect/2, with the external option: https://hexdocs.pm/phoenix/Phoenix.Controller.html#redirect/2

2 Likes

Hello @Nicd,

Thanks for your response.

I tried your suggestion as below:

get “/testurl” do
conn |> Plug.Conn.put_status(:found) |> Plug.Conn.put_resp_header(“location”, “https://google.com”)
end

Below is the result:

Request: GET /testurl
** (exit) an exception was raised:
** (Plug.Conn.NotSentError) a response was neither set nor sent from the connection
(plug_cowboy) lib/plug/cowboy/handler.ex:37: Plug.Cowboy.Handler.maybe_send/2
(plug_cowboy) lib/plug/cowboy/handler.ex:13: Plug.Cowboy.Handler.init/2

Any ideas, please?

Ah, you need to replace Plug.Conn.put_status(:found) with Plug.Conn.resp(:found, "") instead I think. And maybe the header put must be before resp, or after. Can’t remember right now, sorry. :smiley:

1 Like

Thanks so much @Nicd.

It worked finally.
Please find code below:

get “/testurl” do
conn |> Plug.Conn.resp(:found, “”) |> Plug.Conn.put_resp_header(“location”, “https://www.google.com”)
end

2 Likes