Picture this: You've got your Next.js site ready to go. You upload it to S3, feeling pretty good about yourself. But when you hit that URL, Ah?! 404 errors pop up. Why is this happening?

Originally

const nextConfig = {
  output: "export",
  trailingSlash: false,
};

Without the trailingSlash option, next build would generate:

.out/subdirectory-page.html

When you try to access domain.com/subdirectory-page, you'd get a 404 error.

This happens because there's no S3 object named

subdirectory-page

but there is one called

subdirectory-page.html

If you're okay with URLs like domain.com/subdirectory-page.html, this wouldn't be an issue. However, I feel URLs ending with .html REALLY unattractive.

Now

const nextConfig = {
  output: "export",
  trailingSlash: true,
};

With trailingSlash enabled, next build will generate:

.out/subdirectory-page/index.html

After uploading this to your server, you go

domain.com/subdirectory-page

will automatically redirect to

domain.com/subdirectory-page/

The Impact of the Trailing Slash /

The / is used to denote directories. Since next build is configured with trailingSlash=true, it structures each page as a directory, resulting in:

/out/subdirectory-page/index.html

When accessing domain.com/subdirectory-page/, the following occurs

  1. The server locates the subdirectory-page/ directory
  2. It then serves the default index file, which is index.html

When accessing domain.com/subdirectory-page, the process is

  1. The server first checks for an object named subdirectory-page
  2. If not found, it responds with a 302 Found status (note: not a 301), including a header with location: /subdirectory-page/
  3. The browser then uses this header to make a new request for the correct URL