Skip to content

Lesson 32 ยท Deployment and Migration

Redirects, Headers and Custom 404 Pages in Gatsby

Move URLs safely with createRedirect, set cache and security headers, build a useful 404 page and handle trailing slashes in a Gatsby site.

After launch, a site keeps changing: posts are renamed, sections move, old campaign links must keep working. Broken links lose readers and search rankings. This lesson covers the tools that keep URLs healthy: redirects, response headers, error pages and trailing-slash rules.

Redirects with createRedirect

In gatsby-node.js, call createRedirect from actions:

JavaScript
// gatsby-node.js (real Gatsby, read-only)
exports.createPages = ({ actions }) => {
  const { createRedirect } = actions

  createRedirect({ fromPath: "/old-blog/", toPath: "/blog/", isPermanent: true })
  createRedirect({ fromPath: "/docs/v1/*", toPath: "/docs/latest/:splat", statusCode: 301 })
  createRedirect({ fromPath: "/go/shop", toPath: "https://shop.example.com", redirectInBrowser: false })
}

Gatsby itself only performs client-side redirects between its own pages (redirectInBrowser: true). For real HTTP redirects (status 301 or 302), a host adapter or plugin converts these calls into the host's format: a _redirects file on Netlify, vercel.json on Vercel, and so on. Without such support, a static host ignores them. Hosts also let you write rules directly, so check which is simplest for you.

Use 301 (permanent) when a page moved for good: search engines transfer ranking. Use 302 for temporary moves such as a campaign. Redirect to the final address, not through chains (/a to /b to /c), because every hop adds delay.

Redirect rule stand-in

Matching redirects is a small algorithm: exact paths first, then wildcard prefixes with a :splat.

JS Stand-in: apply redirect rules

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Response headers

Headers improve caching and security. Hosts apply them from config files; Gatsby's adapter model and plugins such as gatsby-plugin-netlify (older) or gatsby-config.js headers (with a supporting adapter) can generate them. A sensible baseline:

Path Header Why
/static/* and /*.js, /*.css with hashes Cache-Control: public, max-age=31536000, immutable Hashed files never change.
/*.html, /page-data/* Cache-Control: public, max-age=0, must-revalidate Always check for new content.
/* X-Content-Type-Options: nosniff Stops content-type guessing.
/* Referrer-Policy: strict-origin-when-cross-origin Limits referrer leakage.
/* Content-Security-Policy: ... Restricts where scripts and frames come from.
JavaScript
// gatsby-config.js (real Gatsby, read-only; requires an adapter that supports headers)
module.exports = {
  headers: [
    { source: "/static/*", headers: [{ key: "Cache-Control", value: "public, max-age=31536000, immutable" }] },
    { source: "/*", headers: [{ key: "X-Content-Type-Options", value: "nosniff" }] },
  ],
}

A strict Content Security Policy needs care: Gatsby injects small inline scripts, so a policy may need hashes or 'unsafe-inline' for script-src. Test in report-only mode first.

Custom 404 page

Create src/pages/404.js. Gatsby outputs 404.html, which hosts use for unknown URLs. In development, Gatsby shows its own 404 page that lists existing pages; the one you wrote appears in the production build.

JSX
// src/pages/404.js (real Gatsby, read-only)
import * as React from "react"
import { Link } from "gatsby"

export default function NotFound() {
  return (
    <main>
      <h1>Page not found</h1>
      <p>The page may have moved. Try the <Link to="/blog/">blog</Link> or <Link to="/">home page</Link>.</p>
    </main>
  )
}

export const Head = () => <title>Not found</title>

A helpful 404 offers navigation and search, and returns an HTTP 404 status (hosts do this for 404.html). Do not redirect missing pages to the home page: search engines treat that as a "soft 404".

Trailing slashes

/about and /about/ are different URLs to a server. Gatsby 5 creates pages with a trailing slash by default (trailingSlash: "always"), and the Link component follows the setting. Choose one option and be consistent:

JavaScript
// gatsby-config.js (real Gatsby, read-only)
module.exports = { trailingSlash: "always" } // or "never" or "ignore"

Mismatches create duplicate-content problems and extra redirects. Canonical tags (see SEO) must use the same form.

JS Stand-in: normalize trailing slashes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • Expecting createRedirect to produce HTTP redirects on a plain static host.
  • Redirect chains and loops.
  • Redirecting every 404 to the home page.
  • Mixed trailing-slash styles across links, sitemap and canonical tags.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Which status code tells search engines a page moved permanently?

    301 is a permanent redirect; 302 is temporary.
  2. 2. Which Cache-Control suits files with content hashes in their names?

    A changed file gets a new name, so the old one can be cached for a year.
  3. 3. What is a soft 404?

    Search engines dislike missing pages that answer with 200 or redirect to the home page.

Summary

  • createRedirect describes redirects; a host adapter or file turns them into real HTTP redirects.
  • Prefer 301 for permanent moves and avoid chains.
  • Cache hashed assets for a year and revalidate HTML and page data; add basic security headers.
  • Provide src/pages/404.js and pick one trailing-slash policy.

Next: Upgrading and migrating from Gatsby