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.

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
Back to Router Examples