3

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?

webdeb
  • 12,993
  • 5
  • 28
  • 44
  • Why would you do this on application level? Usually, such rewrites are done on the web server level config. – Aleksei Matiushkin Nov 04 '16 at 06:12
  • true, in this case cowboy is my top level server, no other reverse proxy, thanx – webdeb Nov 04 '16 at 08:58
  • 1
    Then you probably want to use [Cowboy routing](https://ninenines.eu/docs/en/cowboy/2.0/guide/routing/) for that. When I’ve said “why on app level,” I meant that `Plug` is way too deep inside the application for this kind of task. – Aleksei Matiushkin Nov 04 '16 at 10:18
  • 1
    yeah, I gree, but I am a bit confused how to do it with cowboy routing. Can you give a small example? – webdeb Nov 06 '16 at 15:07

1 Answers1

5

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.

Sheharyar
  • 73,588
  • 21
  • 168
  • 215