WwwRedirect
A Plug for redirecting HTTP requests between www and non-www versions of domains.
This library redirects requests between www.example.com and example.com based on your preference.
Installation
If available in Hex, the package can be installed
by adding www_redirect to your list of dependencies in mix.exs:
def deps do
[
{:www_redirect, "~> 0.1.3"}
]
end
Install with Igniter
mix igniter.install www_redirect
Usage
socket "/live" # ...
# Add ONE of the following:
# Redirect to non-www (default behavior)
plug WwwRedirect
# E.g. `www.example.com` -> `example.com`
plug WwwRedirect, to: :non_www
# E.g. `https://example.com/path` -> `https://www.example.com/path`
plug WwwRedirect, to: :www
# Redirect to www temporarily instead of using the default 301 response
plug WwwRedirect, to: :www, status: 302
plug Plug.Static, # ...
Configuration Options
The plug accepts the following options:
:to- Specifies the redirect target. Can be:wwwor:non_www(default).:www- Redirects bare domains to www versions (e.g.,example.com→www.example.com):non_www(default) - Redirects www domains to bare versions (e.g.,www.example.com→example.com)
:status- Specifies the HTTP redirect status as an integer or Plug status atom. Defaults to301(:moved_permanently).
Fixing Tests
Phoenix/Plug sets the conn.host to www.example.com by default, which might break your tests after adding WwwRedirect to your endpoint. Unfortunately, it's not possible to configure the conn.host in test globally since it's a default value but you can update your conn_case.ex like this:
# test/support/conn_case.ex
# ...
setup tags do
# ...
{:ok, conn: Phoenix.ConnTest.build_conn() |> Map.put(:host, "example.com")}
end
This will set the conn.host to example.com instead of www.example.com in all your tests. You can always set it back by running Map.put(conn, :host, "www.example.com") in your test.