How to Create Nested Routes in Astro: Simple Guide
src/pages folder with nested directories. Each folder can have an index.astro file or other page files, which Astro automatically maps to nested URLs reflecting the folder structure.Syntax
Astro uses the src/pages folder to define routes. Nested routes are created by placing folders inside src/pages. Each folder represents a URL segment. Inside folders, an index.astro file serves as the page for that route. Other files inside the folder become sub-routes.
For example, a file at src/pages/blog/index.astro maps to /blog, and src/pages/blog/post.astro maps to /blog/post.
src/pages/ โโโ index.astro // maps to / โโโ about.astro // maps to /about โโโ blog/ โโโ index.astro // maps to /blog โโโ post.astro // maps to /blog/post
Example
This example shows a nested route structure with a homepage, a blog section, and a blog post page. The URLs will be /, /blog, and /blog/post.
---
---
<html>
<body>
<h1>Home Page</h1>
</body>
</html>
---
---
<html>
<body>
<h1>Blog Home</h1>
</body>
</html>
---
---
<html>
<body>
<h1>Blog Post</h1>
</body>
</html>Common Pitfalls
One common mistake is forgetting to add an index.astro file inside a folder, which causes the route to not resolve correctly. Another is naming files incorrectly or using uppercase letters, which can cause unexpected URLs.
Also, avoid placing multiple index.astro files in the same folder, as it will cause conflicts.
// Wrong: Missing index.astro in blog folder src/pages/blog/post.astro // /blog/post works // but /blog will 404 because no index.astro // Right: Add index.astro src/pages/blog/index.astro // /blog works src/pages/blog/post.astro // /blog/post works
Quick Reference
| Concept | Description | Example Path | URL |
|---|---|---|---|
| Root route | Top-level page | src/pages/index.astro | / |
| Nested folder | Folder creates URL segment | src/pages/blog/ | /blog |
| Nested page | File inside folder | src/pages/blog/post.astro | /blog/post |
| Index file | Default page for folder | src/pages/blog/index.astro | /blog |