How to Redirect WWW to no-WWW in Next.js

Updated on

Here’s an easy way to redirect the WWW version of a site to the no-WWW version (or vice versa) in Next.js.

How to Redirect in Next.js

Redirects in Next.js are done in the next.config.mjs file. Here’s a code snippet that shows how to redirect all requests made to www.example.com to their corresponding pages on example.com.

async redirects() {
    return [
        {
            source: "/:path*",
            has: [{ type: "host", value: "www.example.com" }],
            destination: "https://example.com/:path*",
            permanent: true,
        },
    ];
},

Here’s an example next.config.mjs file that shows where the code goes.

/** @type {import('next').NextConfig} */
import { withContentlayer } from "next-contentlayer";

const nextConfig = {
  // This is the redirects section.
  async redirects() {
    return [
      {
        source: "/:path*",
        has: [{ type: "host", value: "www.example.com" }],
        destination: "https://example.com/:path*",
        permanent: true,
      },
      // If you need more redirects, they can be added JS objects here.
    ];
  },

  // Your other Next.js config rules go here.
  // https://nextjs.org/docs/api-reference/next.config.js/introduction
  trailingSlash: true,
  reactStrictMode: true,
  swcMinify: true,
  i18n: {
    locales: ["en"],
    defaultLocale: "en",
  },
};

export default withContentlayer(nextConfig);

If you want to redirect from the no-WWW version to the WWW version, then use this pattern instead.

async redirects() {
    return [
        {
            source: "/:path*",
            has: [{ type: "host", value: "example.com" }],
            destination: "https://www.example.com/:path*",
            permanent: true,
        },
    ];
},

Don’t forget to change example.com to your actual domain name.

For more information, see the Next.js redirect documentation and/or leave a comment below.

Tagged with: SEO Next.jsJavaScript

Feedback and Comments

What did you think about this page? Do you have any questions, or is there anything that could be improved? You can leave a comment after clicking on an icon below.