Q65: What are the differences between rewrites, redirects, and headers in next.config.js?
redirects(): Returns HTTP 301/302 responses, forcing the browser to update its address bar URL to a new location.rewrites(): Acts as an internal proxy. Maps an incoming request URL to a different destination path or external server transparently without updating the browser URL.headers(): Injects custom HTTP headers (CSP, CORS, Security headers) onto matching request responses.
Rewrites and Redirects Declaration
// next.config.mjs
export default {
async redirects() {
return [{ source: '/old-blog/:slug', destination: '/posts/:slug', permanent: true }]; // 301 Redirect
},
async rewrites() {
return [{ source: '/api-proxy/:path*', destination: 'https://backend.internal/:path*' }]; // Proxy
},
};💡 redirects issue 301 browser changes; rewrites proxy requests transparently to internal/external destinations.
Key Takeaways
redirects()changes user browser URL address bar locations.rewrites()maps requests to internal/external destinations proxying content transparently.
Knowledge Check
Which configuration method in next.config.js acts as a transparent proxy mapping incoming paths to external microservices without altering user browser URLs?