Next.js Redirects, Rewrites, and Headers in next.config.ts
Redirect changes the URL, rewrite masks it, headers ride on the response — all evaluated in a fixed order before routing. Permanent means cached in browsers, not just in Google.

Quick Summary
next.config.ts exposes three request-time rule sets — redirects, rewrites, and headers — evaluated on the server before a request is matched to a route. They are configuration, not code: they run without a function invocation, they apply to static assets and pages alike, and they are evaluated in a fixed order.
The distinction that matters: a redirect changes the URL the browser sees (301/308 permanent, 302/307 temporary); a rewrite keeps the URL and serves different content, which is how you mount a new app under /docs or proxy an external API. Headers attach to responses and cannot remove headers the framework sets.
Order is: headers → redirects → middleware/proxy → filesystem (public, _next/static, pages) → rewrites (beforeFiles) → dynamic routes → rewrites (afterFiles) → fallback rewrites. Misreading that order is why a redirect "does not fire" when middleware already handled the path.
Basic Syntax & Core Signatures
// next.config.ts
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
async redirects() {
return [
{
source: "/old-blog/:slug",
destination: "/blog/:slug",
permanent: true, // 308 in App Router
},
{
source: "/docs",
has: [{ type: "cookie", key: "beta", value: "1" }],
destination: "/beta/docs",
permanent: false,
},
{
source: "/legacy/:path*",
destination: "https://legacy.example.com/:path*",
permanent: true,
},
];
},
async rewrites() {
return {
beforeFiles: [
{ source: "/api/legacy/:path*", destination: "https://api.example.com/:path*" },
],
afterFiles: [
{ source: "/docs/:path*", destination: "/documentation/:path*" },
],
fallback: [
{ source: "/:path*", destination: "/404", has: [{ type: "header", key: "x-app", value: "web" }] },
],
};
},
async headers() {
return [
{
source: "/:path*",
headers: [
{ key: "X-Content-Type-Options", value: "nosniff" },
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
],
},
{
source: "/api/:path*",
headers: [{ key: "Cache-Control", value: "no-store" }],
},
];
},
};
export default nextConfig;Matchers use path-to-regexp syntax: :name matches one segment, :name* matches zero or more, :name+ one or more, :name? optional, and (.*) a raw regex group. has and missing add conditions — cookie, header, query, host — which is how you avoid JavaScript for simple A/B or locale switches.
Key Comparison Table
| Rule | Changes browser URL | Status codes | Runs on | Applies to static assets |
|---|---|---|---|---|
redirects() | Yes | 301, 302, 303, 307, 308 | Server, before routing | Yes |
rewrites() | No | n/a, transparent proxy | Server, before and after filesystem | Yes |
headers() | No | n/a | Server, on the response | Yes |
Middleware / proxy.ts | Either, via NextResponse | Any | Edge, before routing | Only if matched |
redirect() in a page | Yes | 307 (308 with permanentRedirect) | Server render | No |
notFound() | No | 404 | Server render | No |
| Status | Method preserved | Cacheable by default | Use |
|---|---|---|---|
| 301 | No, may become GET | Yes, aggressively | Permanent move, no query semantics needed |
| 308 | Yes | Yes, aggressively | Permanent move, POST preserved |
| 302 | No | No | Temporary |
| 307 | Yes | No | Temporary, method preserved |
| 303 | No | No | Post/Redirect/Get after a form |
Practical Edge Cases & Deep Dives
1. permanent: true is cached forever by browsers
In the App Router a permanent redirect is a 308, and browsers cache it at the URL level until the cache is cleared. A typo published with permanent: true is effectively permanent for returning visitors even after you fix it. During a migration, ship permanent: false for a week, confirm traffic, then flip to true. Search engines treat 308 and 301 the same way for link equity.
2. Cookie-based redirect without JavaScript
has: [{ type: "cookie", key: "lang", value: "ko" }] is evaluated per request on the server, so a locale switch can be pure configuration. Two limits: the value must match exactly unless you use a regex, and the rule only fires when the cookie is present on that path. For "cookie absent" use missing:
{
source: "/:path((?!ko|en|ja).*)",
missing: [{ type: "cookie", key: "lang" }],
destination: "/en/:path",
permanent: false,
}The negative-lookahead source must not match an already-localised path, or the rule redirects its own destination and the browser reports a redirect loop.
3. Rewriting to an external URL masks the origin
destination: "https://api.example.com/:path*" proxies the request and returns the upstream body under your domain. The browser sees your URL, so cookies are yours, CORS disappears, and the upstream sees your server's IP. That is convenient and risky: the upstream's set-cookie headers pass through, error pages come from a different domain, and streaming, WebSocket upgrades, and some compression behave differently. Keep proxied paths narrow and add a header rule to strip anything you do not want forwarded.
4. Redirects versus middleware for auth
A redirects() rule cannot read a session token or call a database — it matches static conditions only. Auth redirects belong in middleware (cheap cookie presence) or in the page (verified session). Putting an auth decision in next.config.ts is a common misunderstanding that produces a rule that lets everyone through once the cookie name changes.
5. basePath and trailingSlash interactions
Setting basePath: "/app" prefixes every route, every next/link href, and every public asset path automatically — but not strings you build by hand, and not fetch("/api/x"). trailingSlash: true makes /about redirect to /about/ with a 308; combined with a static export on a host that maps directories to index.html, it is usually required. Both settings change canonical URLs, so update sitemaps and internal links in the same change.
6. Headers that conflict with caching and with the framework
headers() cannot override Cache-Control for a page that Next.js renders dynamically, and it cannot remove a header the framework sets. For security headers on every response including static assets, apply a catch-all source. A strict CSP needs the nonce that middleware can inject, which headers() cannot do because nonces are per request:
export function middleware(req: NextRequest) {
const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
const res = NextResponse.next();
res.headers.set("Content-Security-Policy",
`script-src 'self' 'nonce-${nonce}' 'strict-dynamic'; object-src 'none'`);
return res;
}When a nonce is used, next/script and inline scripts must receive it, or the page breaks in production while working in dev where CSP is often not applied.
A safer sequence for a new CSP: ship it in report-only mode (Content-Security-Policy-Report-Only) with a report-uri, collect violations for a week, then enforce. Shipping an enforcing policy and the nonce change in one deploy usually breaks third-party widgets that load their own scripts, and the breakage only shows on pages you did not test.
Common Runtime & Configuration Mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Redirect loop | Rule's source matches its own destination | Narrow the source, add a missing condition |
| Redirect never fires | Middleware handled the path first, or a page exists at the source | Check evaluation order; remove the page or move the logic |
| Old redirect still served after deploy | 301/308 cached in the browser | Test with curl, use permanent: false during migration |
| Rewrite returns 404 | Destination path does not exist on the target | Verify the upstream path, including trailing slash |
| CSP blocks scripts in production only | Nonce not applied to inline scripts | Pass the nonce to next/script and inline tags |
fetch("/api/x") breaks under basePath | Hand-built absolute path | Prefix with basePath, or use a relative URL from the component |
| Header rule does not apply to images | Source pattern does not match _next/static | Use /:path* or an explicit /_next/static/:path* rule |
Try matching browser tools
All toolsSmall utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Next.js guides
All Next.js guidesNext.js Static Export, Standalone Output, and Docker Deployment
Export has no server, standalone has a pruned one, and the default expects a full install. The three COPY lines that decide whether a container renders CSS.
Next.js Parallel Routes and Intercepting Routes: Slot Layouts and Modals
Named slots render several pages in one layout, and (.) interception makes a click open over the page while a direct link renders the full route. Why every slot needs default.tsx.
Next.js ISR: Route Revalidate, revalidateTag, and On-Demand Invalidation
Two clocks and one trigger: route revalidate seconds, fetch-level tags, and a webhook that calls revalidateTag. A timer is a ceiling on freshness, never a guarantee.
Next.js Environment Variables: NEXT_PUBLIC_, Build-Time Inlining, and Runtime Config
The prefix decides whether a value is compiled into the browser bundle or stays on the server. One image, two environments, and the choice that follows from it.
More in Next.js
All Next.js guidesThe guides filed next to this one in Next.js, in library order.