Use Apache .htaccess file for Next.js static outputs
How to use .htaccess file to serve Next.js static files on Apache server
When deploying a Next.js static export to an Apache web server, proper URL rewriting is needed to handle client-side routing.
Here is my config file of Next.js, how it generates static output from the project.
const path = require('path');
const withPlugins = require('next-compose-plugins');
const { webpack } = require('./next-webpack.config');
const withPWA = require('next-pwa');
module.exports = withPlugins(
[
[
withPWA,
{
pwa: {
disable: process.env.NODE_ENV === 'development',
dest: 'public'
}
}
]
],
{
basePath: '',
reactStrictMode: true,
webpack5: true,
poweredByHeader: false,
trailingSlash: true,
pageExtensions: ['ts', 'tsx'],
sassOptions: {
includePaths: [path.join(__dirname, 'styles')]
},
images: {
disableStaticImages: true,
domains: [],
formats: ['image/avif', 'image/webp']
},
webpack
}
); The Apache server reads .htaccess file from the host directory and process the redirect rules by conditions.
This file contains the following rewrite rules:
- Error document handled by the /404 path
- All requests without matching files redirect to the corresponding .html file
- All requests are served over HTTPS
- The www subdomain redirects to the main domain
- A secondary domain redirects to the main domain
- A tertiary domain redirects to a subpath of the main domain
RewriteEngine On
ErrorDocument 404 https://example.com/404/
RewriteRule ^([^/]+)/$ $1.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.html
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.html
RewriteCond %{SERVER_PORT} 443
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(.[a-zA-Z0-9]{1,5}|/)$
RewriteRule ^(.*)$ https://example.com/$1/ [R=301,L]
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteCond %{SERVER_PORT} 443
RewriteRule ^(.*)$ https://example.com/$1 [R,L]
RewriteCond %{HTTP_HOST} ^example.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [R,L]
RewriteCond %{HTTP_HOST} ^example2.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.example2.com$
RewriteRule ^(.*)$ https://example.com/$1 [R,L]
RewriteCond %{HTTP_HOST} ^example3.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.example3.com$
RewriteRule ^(.*)$ https://example.com/example3/ [R,L] Conclusion
These rewrite rules handle the most common routing scenarios for statically exported Next.js applications on Apache, including clean URLs and trailing slash normalization.