The basics of redirect configuration in AstroJS
Adding static page redirects in AstroJS is very simple: we just have to add entries to the redirects
property of our configuration object.
For example, if we add the following property to the configuration of our AstroJS project, AstroJS will enable a page redirect from <thedomain>/other
to <thedomain>/place
:
redirects: {
'/other': '/place',
}
When building the site with AstroJS, every entry in the redirects
object will be transformed in to a static redirect HTML page.
With the configuration above, a page index.html
will be created in the other
directory of our build output folder (generally, the file will be created at a file path corresponding to the path to be redirected).
The redirection page created by AstroJS index.html
is very simple. It is a simple HTML page that contains two <meta>
tags as shown below:
- the first one tells the browser to redirect the request from; and,
- the second one will tell crawlers to not index the page since it does not contain any real content.
<meta
http-equiv="refresh"
content="0;url=https://<thedomain>/other"
/><meta name="robots" content="noindex" /><link
rel="canonical"
href="https://<thedomain>/place"
/>
The page will also contain an anchor element in the body that can be clicked in case the automatic redirect does not work.
By default, AstroJS uses static
output mode (server side rendering, SSR). In this mode, the redirect status code is not configurable. I.e. the redirect will always have status code 301 Moved Permanently.
Importing a list of static redirects
For AstroJS TypeScript projects, we may also import the redirects in JSON format from an external file.
E.g. let’s assume src/config/redirects.json
contains the following:
{
"/other": "/place"
}
Then, using the magic of JSON module support in TypeScript (the TypeScript compiler option resolveJsonModule
), we may simply import the redirect configuration via the module system.
// …
import redirects from "./src/config/redirects.json"
// …
export default defineConfig({
// …
redirects,
// …
});
// …
If we extend, the astro/tsconfigs/strict
TypeScript configuration, this is already activated and we can directly import JSON in our AstroJS configuration and add it to the config object:
This is not only a pretty neat feature but also reduces clutter in the configuration file and makes it easier to read.