How to get the current phoenix URL

I would like to know the current url with the elixir / phoenix framework, how can I get this?

Edit # 1 :

My nginx config file:

server { client_max_body_size 100M; listen 80; server_name *.babysittingbordeaux.dev *.babysittingparis.dev access_log /usr/local/var/log/nginx/baby-access.log; error_log /usr/local/var/log/nginx/baby-error.log; location / { proxy_pass http://127.0.0.1:4000; } } 

the code:

 Atom.to_string(conn.scheme) <> "://" <> (Enum.into(conn.req_headers, %{}) |> Map.get("host")) <> conn.request_path 

This example returns http: //127.0.0.1-00-00000/ , I would like to get http://www.babysittingbordeaux.dev/

I work in development mode.

+7
elixir phoenix-framework
source share
3 answers

If you are only interested in the request path, you can use conn.request_path , which contains a value like "/users/1" .

To get the url including host you can use

 MyApp.Router.Helpers.url(conn) <> conn.request_path 

which will return a result, for example, "http://localhost:4000/users/1" .

+7
source share

I'm not sure which is the best method.

But something like this is possible as an illustration inside the IndexController .

  def index(conn, params) do url_with_port = Atom.to_string(conn.scheme) <> "://" <> conn.host <> ":" <> Integer.to_string(conn.port) <> conn.request_path url = Atom.to_string(conn.scheme) <> "://" <> conn.host <> conn.request_path url_phoenix_helper = Tester.Router.Helpers.index_url(conn, :index, params["path"]) # <-- This assumes it is the IndexController which maps to index_url/3 url_from_endpoint_config = Atom.to_string(conn.scheme) <> "://" <> Application.get_env(:my_app, MyApp.Endpoint)[:url][:host] <> conn.request_path url_from_host_header = Atom.to_string(conn.scheme) <> "://" <> (Enum.into(conn.req_headers, %{}) |> Map.get("host")) <> conn.request_path text = ~s""" url_with_port :: #{url_with_port} url :: #{url} url_phoenix_helper :: #{url_phoenix_helper} url_from_endpoint_config :: #{url_from_endpoint_config} url_from_host_header :: #{url_from_host_header} """ text(conn, text) end 
+3
source share

You can use Phoenix.Controller.current_url / 1 :

 current_url(conn) 

The endpoint configuration will determine the URL:

 config :my_app_web, MyAppWeb.Endpoint, url: [host: "example.com"] 
+1
source share

All Articles