Permanent 301 Redirects in Phoenix

elixir elixir-phoenix
Posted on: 2017-11-17

In Elixir's Phoenix framework, responding with a redirection response of 302 Found is simple:

conn
|> redirect(to: some_path(conn, :some_action))

Today I was wondering how to do a permanent redirect, with status 301 Moved Permanently.

A glance at the Phoenix source code linked from the docs for redirect/2 made it clear: the response will use a previously-set conn.status if there is one. So a 301 redirect is as simple as:

#!elixir
conn
|> put_status(:moved_permanently)
|> redirect(to: some_path(conn, :some_action))

Testing this is also simple. You just have to change this:

#!elixir
assert redirected_to(conn) == some_path(conn, :some_action)

to this:

#!elixir
assert redirected_to(conn, :moved_permanently) == some_path(conn, :some_action)

In both the controller and the test, you can use 301 in place of :moved_permanently, but I prefer the clarity of using the atom.