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?

Everything below is how an S3 bucket with static website hosting behaves (the website endpoint): a 302 when the slash is missing, a 404 when the file is not there. A bucket kept private behind CloudFront with OAC, like this site, is read through the REST endpoint instead: S3 never redirects, a missing key is a 403, and both the redirect (a 301 there) and the index.html are done by a CloudFront Function.

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