3

如何在phoenix中重写一个Url?
例如将所有请求重写//www.app.com/xyz//app.com/xyz

是否有一个简单的选择,例如force_ssl?有谁知道,在哪里插入?有插件选项吗?

4

1 回答 1

4

Use a Custom Plug

You can write a custom Plug to handle your scenario. Here's an example:

defmodule MyApp.Plugs.RewriteURL do
  import Plug.Conn
  import Phoenix.Controller

  @redirect_from "www.app.com"
  @redirect_to   "app.com"

  def init(default), do: default

  def call(%Plug.Conn{host: host, port: port, request_path: path} = conn, _) do
    if host == @redirect_from do
      conn
      |> redirect(external: "http://#{@redirect_to}:#{port}#{path}")
      |> halt
    else
      conn
    end
  end
end

Now just add it to the top of your pipeline in web/router.ex:

pipeline :browser do
  plug MyApp.Plugs.RewriteURL
  plug :accepts, ["html"]

  # Other plugs...
end

This is a basic proof of concept, but should work for the majority of the cases.

You'll have to modify this code according to your exact requirements since it is missing some functionality. For example, it doesn't pass the request's query or params to the redirected URL. It also does a basic redirect, so you might consider using a 307 redirect if you would like to keep the original request method without changing it to GET.

于 2016-11-07T01:38:50.303 回答