Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readNext.js
#Next.js#Configuration#Routing#SEO
3D illustration of request arrows hitting a config panel that splits into redirect, rewrite and header routes

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

ts
// 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

RuleChanges browser URLStatus codesRuns onApplies to static assets
redirects()Yes301, 302, 303, 307, 308Server, before routingYes
rewrites()Non/a, transparent proxyServer, before and after filesystemYes
headers()Non/aServer, on the responseYes
Middleware / proxy.tsEither, via NextResponseAnyEdge, before routingOnly if matched
redirect() in a pageYes307 (308 with permanentRedirect)Server renderNo
notFound()No404Server renderNo
StatusMethod preservedCacheable by defaultUse
301No, may become GETYes, aggressivelyPermanent move, no query semantics needed
308YesYes, aggressivelyPermanent move, POST preserved
302NoNoTemporary
307YesNoTemporary, method preserved
303NoNoPost/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.

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:

ts
{ 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:

ts
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

SymptomCauseFix
Redirect loopRule's source matches its own destinationNarrow the source, add a missing condition
Redirect never firesMiddleware handled the path first, or a page exists at the sourceCheck evaluation order; remove the page or move the logic
Old redirect still served after deploy301/308 cached in the browserTest with curl, use permanent: false during migration
Rewrite returns 404Destination path does not exist on the targetVerify the upstream path, including trailing slash
CSP blocks scripts in production onlyNonce not applied to inline scriptsPass the nonce to next/script and inline tags
fetch("/api/x") breaks under basePathHand-built absolute pathPrefix with basePath, or use a relative URL from the component
Header rule does not apply to imagesSource pattern does not match _next/staticUse /:path* or an explicit /_next/static/:path* rule

Try matching browser tools

All tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.