heroku - Redirect Elixir Phoenix request from root domain to www -


we have phoenix app on heroku dns @ route 53. followed blog post set proper http https redirect:
http://building.vts.com/blog/2015/11/02/route53-ssl-naked-domain-redirect/

everything works , remaining redirecting root subdomain www.

is there recommended way set in phoenix way?

simply plug in redirect @ top of app's endpoint.

in lib/app/endpoint.ex:

defmodule app.endpoint   use phoenix.endpoint, otp_app: :app    socket "/socket", app.usersocket    plug app.plugs.wwwredirect   # ... end 

in lib/app/plugs/www_redirect.ex:

defmodule app.plugs.wwwredirect   import plug.conn    def init(options)     options   end    def call(conn, _options)     if bare_domain?(conn.host)       conn         |> phoenix.controller.redirect(external: www_url(conn))         |> halt     else       conn # since plugs need return connection     end   end    # returns url www prepended given connection. note   # applies hosts contain "www"   defp www_url(conn)     "#{conn.scheme}://www.#{conn.host}"   end    # returns whether domain bare (no www)   defp bare_domain?(host)     !regex.match?(~r/\awww\..*\z/i, host)   end end 

note you'll need restart sever have effect since nothing in lib reloaded.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -