Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect Elixir Phoenix request from root domain to www

We have a Phoenix app on Heroku with DNS at Route 53. We followed this blog post to set up the proper http to https redirect:
http://building.vts.com/blog/2015/11/02/route53-ssl-naked-domain-redirect/

Everything works and all that is remaining is redirecting the root to the subdomain www.

Is there a recommended way to set this up in a Phoenix way?

like image 948
realdeal Avatar asked Feb 29 '16 04:02

realdeal


2 Answers

Simply plug in the redirect at the top of your app's endpoint.

In lib/app/endpoint.ex:

defmodule App.Endpoint do
  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 do
  import Plug.Conn

  def init(options) do
    options
  end

  def call(conn, _options) do
    if bare_domain?(conn.host) do
      conn
        |> Phoenix.Controller.redirect(external: www_url(conn))
        |> halt
    else
      conn # Since all plugs need to return a connection
    end
  end

  # Returns URL with www prepended for the given connection. Note this also
  # applies to hosts that already contain "www"
  defp www_url(conn) do
    "#{conn.scheme}://www.#{conn.host}"
  end

  # Returns whether the domain is bare (no www)
  defp bare_domain?(host) do
    !Regex.match?(~r/\Awww\..*\z/i, host)
  end
end

Note that you'll need to restart your sever for this to have an effect since nothing in lib is reloaded.

like image 162
fny Avatar answered Oct 24 '22 10:10

fny


You can also use plug_canonical_host to take care of it for you and ensure that your Elixir application is only accessible through its canonical URL.

like image 34
remi Avatar answered Oct 24 '22 08:10

remi