#Routes
3 messages · Page 1 of 1 (latest)
You're right about the issue with your route configuration. When using a rest parameter like [...locale] in your file path, Astro will match any value at that position in the URL without validation by default.
The reason you're not seeing a 404 page is that the rest parameter (...) in dynamic routes will match any path segment, regardless of whether it's a valid locale or not. Your /pages/[...locale]/index.astro file is essentially telling Astro to render that page for any value that appears in that position.
To fix this issue, you have a few options:
- Use server-side validation: In SSR mode, you can check if the locale is valid inside your page component and redirect to a 404 page if needed:
---
const { locale } = Astro.params;
const validLocales = ['en', 'fr', 'es']; // your supported locales
if (!validLocales.includes(locale)) {
return Astro.redirect("/404");
}
---
- Use Astro's i18n routing: If you're handling internationalization, consider using Astro's built-in i18n routing which provides better validation:
// astro.config.mjs
export default defineConfig({
i18n: {
locales: ["es", "en", "fr"],
defaultLocale: "en"
}
})
With this configuration, you would organize your content in locale-specific folders, and Astro would handle the routing and validation for you Internationalization (i18n) Routing.
- Use
getStaticPaths()for static sites: If you're building a static site, you can usegetStaticPaths()to explicitly define which paths should be generated:
---
export function getStaticPaths() {
return [
{ params: { locale: 'en' } },
{ params: { locale: 'fr' } },
{ params: { locale: 'es' } }
];
}
const { locale } = Astro.params;
---
This approach will only generate pages for the specified locales and return 404 for any other values Dynamic routes.