Handling redirects in Netlify
Netlify is a static hosting platform with a git-based deployment system for hosting frontend applications. The built files are delivered via a CDN
Talk about serverless!
So how then do we handle redirection? Thankfully, Netlify has a pretty nifty way to redirect routes which we'll be looking at below.
There are two ways to implement redirection on Netlify.
- Using the
_redirects
file - File-based configuration with
netlify.toml
Using the _redirects
file
To use this method, create a _redirects
file in a folder that's supposed to be the root of your site.
For example /static
or /public
, it all depends on your project's configuration.
Each redirect rule needs to be placed on a new line like this:
# lines like these are ignored
/ https://newsite.com
Looking at the snippet above, when a user navigates to your site's homepage, they get redirected to the new URL specified on the same line after the old URL.
Lines that begin with #
are ignored, so they're useful form making comments.
Specifying custom status codes
By default, all redirect rules have a status code of 301
but to specify a custom status code, you can add that after the new URL like this:
/content /blog 302
Now, the server will respond with a status code of 302
. The 301
redirect indicates a permanent redirect while the 302
indicates a temporary one.
Other response codes could be used, like 404
and 200
.
Splats
An asterisk (*
) after the old URL indicates a splat. A splat represents the remaining parts of the URL after the previous /
.
/content/* /blog/:splat
Navigating to /content/a-random-post
will redirect to /blog-a-random-post
.
Shadowing
If a file currently being navigated to exists, the content of the file would still be rendered. However, you can force the redirection by appending an exclamation (!
) to the new URL.
/blog/* /blog/index.html! 200
Navigating to /blog/new-post.html
will redirect to /blog/index.html
no matter what.
File-based configuration with Netlify.toml
The netlify.toml
file is used for configuring Netlify outside the dashboard, it also provides a more structured way to handle redirection with more options.
Every redirect rule is written below a line starting with [[redirects]]
[[redirects]]
from = "/content/*"
to = "blog/:splat"
status = 301
force = true
By now you must be familiar with the first three rules above, the force
rule is equivalent to the !
in the _redirects
file.
There are more options for the file-based redirects option here.
Roundup
If you happen to have both files in your site's root directory, the _redirects
file usually has the highest priority than the netlify.toml
file in terms of redirects.
Also, more specific redirection rules also have higher priority than generic ones.
/blog/index.html /index.html 302
/blog/* /articles/:splat 301
All navigations to /blog
except the /blog/index.html
file will be redirected to the /articles
route.