'How to get the current url in phoenix framework
I would like to know the current url with elixir / phoenix framework, how I can get this ?
Edit #1:
My nginx config file:
server {
        client_max_body_size 100M;
        listen  80;
        server_name *.example.dev *.example2.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;
        }
}
Code:
Atom.to_string(conn.scheme) <> "://" <> (Enum.into(conn.req_headers, %{}) |> Map.get("host")) <> conn.request_path
That example returns http://127.0.0.1:4000/, I would like to get http://www.example.dev/
I'm in development mode.
Solution 1:[1]
If you are interested only in the request path you can use conn.request_path which holds a value like "/users/1".
To get the URL including the host you can use
MyApp.Router.Helpers.url(conn) <> conn.request_path
which would return a result like "http://localhost:4000/users/1".
Solution 2:[2]
You can use Phoenix.Controller.current_url/1:
current_url(conn)
The endpoint configuration will define the URL:
config :my_app_web, MyAppWeb.Endpoint, url: [host: "example.com"]
    					Solution 3:[3]
I'm not sure which is the best method.
But maybe something like this as an illustration inside 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
    					Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | |
| Solution 2 | Dan | 
| Solution 3 | 
