将Elixir Phoenix请求从根域重定向到www

时间:2016-02-29 04:26:55

标签: redirect heroku elixir phoenix-framework

我们在路线53上使用DNS在Heroku上安装了一个Phoenix应用程序。我们按照此博客文章设置正确的http到https重定向:
http://building.vts.com/blog/2015/11/02/route53-ssl-naked-domain-redirect/

一切正常,剩下的就是将根重定向到子域名www。

是否有推荐的方式以菲尼克斯方式进行设置?

2 个答案:

答案 0 :(得分:8)

只需在应用终端顶部的重定向中plug

lib/app/endpoint.ex

defmodule App.Endpoint do
  use Phoenix.Endpoint, otp_app: :app

  socket "/socket", App.UserSocket

  plug App.Plugs.WWWRedirect
  # ...
end

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

请注意,您需要重新启动服务器才能生成nothing in lib is reloaded以后的效果。

答案 1 :(得分:2)

您也可以使用plug_canonical_host为您处理,并确保您的Elixir应用程序只能通过其规范网址访问。

相关问题