Caddy — Redirect (Sub)Domains

Caddy is a powerful open-source web server, like nginx or Apache. You can configure website redirects as you can do on all other web servers. You can configure redirects in a single line.

This tutorial shows you how to configure redirects from one (sub)domain to another.

Caddy Series Overview

Redirect a (Sub)Domain

We’re using Caddy to serve the superchargejs.com website. We’ve also configured a www.superchargejs.com subdomain pointing to the same server as the root domain. The www subdomain is mainly configured for consistency reasons because in the early days of the web everything started with www.

We want all traffic to go to superchargejs.com. Requests to the www.superchargejs.com subdomain should redirect to the root domain to have a single source of content.

Redirect Between Domains

In Caddy, you can use the redir directive to redirect requests from one domain to another. The redir directive accepts the target as an argument:

www.superchargejs.com {  
  redir https://superchargejs.com
}

Notice: this configuration doesn’t preserve the URI. Read the next paragraph to keep the full request URI in the redirect.

Redirect and Preserve the URI

Here’s a sample Caddy configuration redirecting the requests from www.superchargejs.com to the root domain superchargejs.com and preserves the existing URI:

Caddyfile

www.superchargejs.com {  
  redir https://superchargejs.com{uri}
}

Permanent Redirect

Caddy also supports permanent redirects on the webserver level. You may pass the permanent keyword a second argument to the redir directive:

Caddyfile

www.superchargejs.com {  
  redir https://superchargejs.com{uri} permanent
}

Permanent redirects use a 301 HTTP status code telling the browsers that the source moves permanently to the new location.

Enjoy Caddy redirects!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.