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
- File-based configuration with
To use this method, create a
_redirects file in a folder that's supposed to be the root of your site.
/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.
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
301 redirect indicates a permanent redirect while the
302 indicates a temporary one.
Other response codes could be used, like
An asterisk (
*) after the old URL indicates a splat. A splat represents the remaining parts of the URL after the previous
/content/a-random-post will redirect to
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
/blog/new-post.html will redirect to
/blog/index.html no matter what.
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]] 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
There are more options for the file-based redirects option here.
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