I want to add “.html” extension to the end of a URL in Next.js because S3 origins with CloudFront hosting without CloudFront functions doesn’t work without fullpath except root directory.
How can I add “.html” to the end of a URL in Next.js?
I tried “trailingSlash” option with false, but it doesn’t work because “.html” extension is not added.
1
1. Update next.config.js with Rewrites
In your next.config.js
, you can add a custom rewrite rule that appends .html to the paths.
app/
profile.html/
page.tsx
// next.config.js
module.exports = {
async rewrites() {
return [
{
source: '/:path*', // Match all paths
destination: '/:path*.html', // Append ".html" to all paths
},
];
},
};
2. Middleware Option
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
// If the URL doesn't have an extension and it's not the root URL
if (!pathname.endsWith('.html') && pathname !== '/') {
// Rewrite the URL to add '.html'
const url = req.nextUrl.clone();
url.pathname = `${pathname}.html`;
return NextResponse.rewrite(url);
}
// Continue the request if it already ends with '.html'
return NextResponse.next();
}
export const config = {
matcher: ['/((?!api|_next|favicon.ico).*)'], // Apply to all pages except API, _next, and favicon
};