【问题标题】:Redirect Elixir Phoenix request from root domain to www将 Elixir Phoenix 请求从根域重定向到 www
【发布时间】:2016-02-29 04:26:54
【问题描述】:

我们在 Heroku 上有一个 Phoenix 应用,在 Route 53 使用 DNS。我们按照这篇博文设置了正确的 http 到 https 重定向:
http://building.vts.com/blog/2015/11/02/route53-ssl-naked-domain-redirect/

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

有没有推荐的方法以凤凰方式进行设置?

【问题讨论】:

    标签: redirect heroku elixir phoenix-framework


    【解决方案1】:

    只需在应用端点顶部的重定向中输入 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 以来,您需要重新启动服务器才能生效。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2012-09-27
        • 1970-01-01
        • 2017-03-24
        • 2020-08-28
        • 2015-02-25
        • 1970-01-01
        • 1970-01-01
        • 2015-04-20
        • 1970-01-01
        相关资源
        最近更新 更多