Rewrite Demonstration
Learn how Astro handles URL rewrites
Rewrite
- URL stays the same
- Content comes from different source
- No additional HTTP request
- Better for SEO and UX
Redirect
- URL changes in browser
- Additional HTTP request
- User sees URL change
- Good for permanent moves
How Astro Rewrites Work
Page Rewrites
Use Astro.rewrite() to serve different content while keeping the original URL.
---
// Show localized content based on region
const region = getRegionFromIP(Astro.clientAddress);
if (region === 'EU') {
return Astro.rewrite('/eu/privacy-policy');
}
if (region === 'CA') {
return Astro.rewrite('/ca/privacy-policy');
}
---
<h1>Default Privacy Policy</h1> Middleware Rewrites
Rewrite requests in middleware for powerful URL manipulation.
// src/middleware.ts
export const onRequest = async (context, next) => {
const url = new URL(context.request.url);
// A/B testing
if (url.pathname === '/landing' && Math.random() < 0.5) {
return context.rewrite('/landing-variant-b');
}
// Handle 404s gracefully
const response = await next();
if (response.status === 404) {
return context.rewrite('/custom-404');
}
return response;
}; Common Rewrite Use Cases
๐ Internationalization
Serve localized content based on user location or preferences without changing the URL.
๐งช A/B Testing
Show different page variants to users while maintaining consistent URLs for analytics.
๐ก๏ธ Graceful Fallbacks
Handle errors elegantly by rewriting to custom error pages or fallback content.
๐ฑ Device-Specific
Serve mobile-optimized pages for mobile users while keeping desktop URLs.
โก Feature Flags
Toggle features on/off by rewriting to different implementations based on flags.
๐ SEO Optimization
Serve SEO-optimized content for bots while keeping rich UX for users.
Try Rewrite Examples
๐ Rewrite to Static Content
Same URL, different content source
โก Rewrite to Dynamic Content
URL stays, content varies by user
๐ Rewrite to Localized Content
Region-specific content delivery
๐ก๏ธ Rewrite to Fallback Content
Graceful error handling
Current Request Information
Original URL:
https://scalable-frontend.pages.dev/apps/router/rewrite-demo Query Params:
none Key Differences: Rewrite vs Redirect
| Aspect | Rewrite | Redirect |
|---|---|---|
| URL in Browser | โ Stays the same | โ Changes |
| HTTP Requests | โ Single request | โ Multiple requests |
| SEO Impact | โ Preserves URL authority | โ ๏ธ May transfer authority |
| User Experience | โ Seamless | โ ๏ธ Visible change |
| Use Case | Content variations | Permanent moves |