Search code examples
elixirphoenix-frameworkcowboyplug

RewriteUrl in Phoenix / Plug / Cowboy?


How to rewrite an Url in phoenix?
For example rewrite all requests to //www.app.com/xyz to //app.com/xyz

Is there an easy option for it, like force_ssl? Has anyone an idea, where to PLUG it in? Has plug an option for it?


Solution

  • 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.