This approach uses client-side redirects by using a
<meta http-equiv="refresh" content="0;url=new-url" />
tag in the document head
The content portion of the meta-tag is made up of two parts. The first part (a number) specifies the amount of seconds the browser should wait before applying the redirect.
The second part specifies the new url to push the user to.
I have placed my redirect data into the following JSON file:
/* /public/data/redirects.json */
{
"entries": [
{
"from": "poke",
"to": "/pokemon/list"
},
{
"from": "test-redirect",
"to": "/blog/redirects#managing-your-redirects",
"seconds": 5
},
...
]
}It’s a list of objects with properties from, to, and seconds.
seconds is used to allow some time for the client-redirect to occur, and we will see a count-down implementation later on.
The meta tag allows for specifying a value in seconds that the browser will wait before actually applying the redirect.
Try it out! /test-redirect You should return to this section after 5 seconds.I have created astro page […redirs].astro in /src/pages
I placed my redirects.json file in the /public/data folder.
And the contents of my page are:
/* /src/pages/[...redirs].astro */
---
import redirects from './../../public/data/redirects.json';
export async function getStaticPaths() {
let ary = [];
redirects.entries.forEach((entry) => {
ary.push({
params: { redirs: entry.from },
props: { to: entry.to, seconds: entry.seconds }
});
});
return ary;
}
let seconds = Astro.props.seconds || 0;
let to = Astro.props.to;
let content = `${seconds};url=${to}`;
---
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content={content} />
<style>
* {font-family:arial;}
.msg {margin:20px auto;max-width:400px;border-radius:10px;background:#cdf;padding:20px;text-align:center;}
</style>
</head>
<body>
<div class="msg">
Redirecting in <span id="time-left">{seconds}</span>...
<br/><br/>> <small>{to}</small>
</div>
<script type="text/javascript" define:vars={{seconds}}>
function update() {
seconds -= 1;
document.getElementById('time-left').innerText = seconds;
}
setInterval(update, 1000);
</script>
</body>
</html>The front-matter section imports the JSON data, and is used in the getStaticPaths() function to generate a page per redirect entry.
The static paths contain the following props:
to - the page we are forwarding the user to.seconds - the time the browser will wait before applying the redirect.The html section contains:
meta refresh tagHere is a minimal no whistles version for 0 second redirects:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content={content} />
</head>
</html>During development in Astro, the catch-all rule will take over any 404s.
The expected behavior will work on a built site.
Use server-side redirects when you can.
Here is some more information I collected while researching