Throughout December we'll be highlighting a different Netlify feature each day. ItΒ might just be the thing you need to unlock those creative juices, and dust off that domain you registered but never deployed! Keep an eye on the blog and on Twitter for each feature!
If you've used Netlify Functions before, you may know that one way to trigger them is to visit your site with the path /.netlify/functions/<your function name>
. However, if you wanted to expose your functions as an API, this doesn't look super user-friendly. Instead, we can use redirects to improve it!
We've made setting up redirects in your app easier so you can get started quickly. Let's have a look!
First, you need to create a _redirects
file in the publish directory of your site.
In this file, we can define our redirects with the following syntax:
/api/* /.netlify/functions/:splat 200
In the code sample above, the asterisk (*
) is used to indicate anything that follows /api/
will be matched to anything that follows /.netlify/functions/
. For example, if you are selling products and want to have an API endpoint available such as /api/products
, it will be matched to your functions products.js
available at /.netlify/functions/products
.
Additionally, you can add other options like a HTTP status code, query parameters, redirect by country or language, and more!
For example, if you wanted to redirect to /produits
instead of /products
for people in France, you would specify it this way:
/api/produits /.netlify/functions/products 302 Country=fr
For more details about the different options available and how to use them, check out our docs.
Another way to set up redirects in your app is via the netlify.toml
file.
If we take the same example as the one above, the syntax in the netlify.toml
file would be:
[[redirects]]
from = "/api/*"
to = "/.netlify/functions/:splat"
status = 200
As with the _redirects
file, you can use additional options if you need to pass headers, conditions, query parameters, and more, for more complex applications.
Check out our docs for more information about redirects and rewrites!
Top comments (1)
How can I redirect a page that's on a subroute? i. e. from /adventcado to /adventcado/2021/?