![](/img/trans.png)
[英]Redirect from the domain with www to the root domain - working but not completely properly
[英]Redirect Elixir Phoenix request from root domain to www
我們在Route 53上有一個關於Heroku的Phoenix應用程序和DNS。我們按照這篇博文來設置正確的http到https重定向:
http://building.vts.com/blog/2015/11/02/route53-ssl-naked-domain-redirect/
一切正常,剩下的就是將根重定向到子域www。
是否有推薦的方式以Phoenix方式設置它?
只需插入應用終端頂部的重定向即可。
在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
請注意,您需要重新啟動服務器才能生效,因為重新加載了lib
中的任何內容 。
您還可以使用plug_canonical_host
來為您處理它,並確保您的Elixir應用程序只能通過其規范URL訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.