Exporting a NextJS app with correct static page routes on the server
When exporting a NextJS application ("build": "next build && next export") to the default out folder, the static pages get exported to .html files.
The issue with this is, when navigating to mydomain.com/about from the home page (mydomain.com) it works well but if you hit a hard refresh then you'll get a 404.
That's because NextJS converted the static pages to .html (about.html) which is what we upload to the server. So the link becomes mydomain.com/about.html and not mydomain.com/about.
One solution is to add this to next.config.js :
module.exports = {
trailingSlash: true,
}
This would create a folder with the route name and have an index.html file in this folder. But I don't like the fact that trailingSlash: true or exportTrailingSlash: true, creates a folder with a single index.html in it for every route I have. That would look cluttersome if we had like 25 folders for 25 route pages.
If you upload the exported out folder to a server that supports URL rewrites like Apache httpd or nginx you can create re-writes for your routes. More work, but works well.
Create a file called .htaccess in the public folder and add this :
RewriteEngine On
RewriteRule ^about$ about.html
Now when you goto mydomain.com/about it'll fetch mydomain.com/about.html
About the author
- I am a web developer from Navi Mumbai. Mainly dealt with LAMP stack, now into Django and getting into Laravel and Cloud. Founder of nerul.in and gaali.in
Comments
Join the discussionNo comments yet. Be the first to comment.





